diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ApiResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ApiResponseFormat.cs new file mode 100644 index 000000000000..b2bd551420ac --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ApiResponseFormat.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Possible API response formats. + public readonly partial struct ApiResponseFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ApiResponseFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string TextValue = "text"; + private const string JsonObjectValue = "json_object"; + + /// `text` format should be used for requests involving any sort of ToolCall. + public static ApiResponseFormat Text { get; } = new ApiResponseFormat(TextValue); + /// Using `json_object` format will limit the usage of ToolCall to only functions. + public static ApiResponseFormat JsonObject { get; } = new ApiResponseFormat(JsonObjectValue); + /// Determines if two values are the same. + public static bool operator ==(ApiResponseFormat left, ApiResponseFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ApiResponseFormat left, ApiResponseFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ApiResponseFormat(string value) => new ApiResponseFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ApiResponseFormat other && Equals(other); + /// + public bool Equals(ApiResponseFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.Serialization.cs index 7f7c124b0054..de33b338f1ec 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.Serialization.cs @@ -68,13 +68,52 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteObjectValue(item, options); } writer.WriteEndArray(); - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) + if (ToolResources != null) { - writer.WriteStringValue(item); + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } + if (Temperature != null) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + if (Optional.IsDefined(ResponseFormat)) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); + } } - writer.WriteEndArray(); if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -136,7 +175,10 @@ internal static Assistant DeserializeAssistant(JsonElement element, ModelReaderW string model = default; string instructions = default; IReadOnlyList tools = default; - IReadOnlyList fileIds = default; + ToolResources toolResources = default; + float? temperature = default; + float? topP = default; + BinaryData responseFormat = default; IReadOnlyDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -202,14 +244,44 @@ internal static Assistant DeserializeAssistant(JsonElement element, ModelReaderW tools = array; continue; } - if (property.NameEquals("file_ids"u8)) + if (property.NameEquals("tool_resources"u8)) { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + if (property.Value.ValueKind == JsonValueKind.Null) { - array.Add(item.GetString()); + toolResources = null; + continue; + } + toolResources = ToolResources.DeserializeToolResources(property.Value, options); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; } - fileIds = array; + responseFormat = BinaryData.FromString(property.Value.GetRawText()); continue; } if (property.NameEquals("metadata"u8)) @@ -242,7 +314,10 @@ internal static Assistant DeserializeAssistant(JsonElement element, ModelReaderW model, instructions, tools, - fileIds, + toolResources, + temperature, + topP, + responseFormat, metadata, serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.cs index 34402e5480d9..09b938b95c0e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.cs @@ -56,17 +56,29 @@ public partial class Assistant /// /// The collection of tools enabled for the assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . + /// + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. /// - /// A list of attached file IDs, ordered by creation date in ascending order. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - /// , , or is null. - internal Assistant(string id, DateTimeOffset createdAt, string name, string description, string model, string instructions, IEnumerable tools, IEnumerable fileIds, IReadOnlyDictionary metadata) + /// , or is null. + internal Assistant(string id, DateTimeOffset createdAt, string name, string description, string model, string instructions, IEnumerable tools, ToolResources toolResources, float? temperature, float? topP, IReadOnlyDictionary metadata) { Argument.AssertNotNull(id, nameof(id)); Argument.AssertNotNull(model, nameof(model)); Argument.AssertNotNull(tools, nameof(tools)); - Argument.AssertNotNull(fileIds, nameof(fileIds)); Id = id; CreatedAt = createdAt; @@ -75,7 +87,9 @@ internal Assistant(string id, DateTimeOffset createdAt, string name, string desc Model = model; Instructions = instructions; Tools = tools.ToList(); - FileIds = fileIds.ToList(); + ToolResources = toolResources; + Temperature = temperature; + TopP = topP; Metadata = metadata; } @@ -90,12 +104,26 @@ internal Assistant(string id, DateTimeOffset createdAt, string name, string desc /// /// The collection of tools enabled for the assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . + /// + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. /// - /// A list of attached file IDs, ordered by creation date in ascending order. + /// The response format of the tool calls used by this assistant. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal Assistant(string id, string @object, DateTimeOffset createdAt, string name, string description, string model, string instructions, IReadOnlyList tools, IReadOnlyList fileIds, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal Assistant(string id, string @object, DateTimeOffset createdAt, string name, string description, string model, string instructions, IReadOnlyList tools, ToolResources toolResources, float? temperature, float? topP, BinaryData responseFormat, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; @@ -105,7 +133,10 @@ internal Assistant(string id, string @object, DateTimeOffset createdAt, string n Model = model; Instructions = instructions; Tools = tools; - FileIds = fileIds; + ToolResources = toolResources; + Temperature = temperature; + TopP = topP; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -131,11 +162,71 @@ internal Assistant() /// /// The collection of tools enabled for the assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IReadOnlyList Tools { get; } - /// A list of attached file IDs, ordered by creation date in ascending order. - public IReadOnlyList FileIds { get; } + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + public ToolResources ToolResources { get; } + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + public float? Temperature { get; } + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + public float? TopP { get; } + /// + /// The response format of the tool calls used by this assistant. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ResponseFormat { get; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IReadOnlyDictionary Metadata { get; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.Serialization.cs index 28455a04d327..c906e565aced 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.Serialization.cs @@ -74,15 +74,60 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead } writer.WriteEndArray(); } - if (Optional.IsCollectionDefined(FileIds)) + if (Optional.IsDefined(ToolResources)) { - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) + if (ToolResources != null) { - writer.WriteStringValue(item); + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } + } + if (Optional.IsDefined(Temperature)) + { + if (Temperature != null) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + } + if (Optional.IsDefined(TopP)) + { + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + } + if (Optional.IsDefined(ResponseFormat)) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); } - writer.WriteEndArray(); } if (Optional.IsCollectionDefined(Metadata)) { @@ -145,7 +190,10 @@ internal static AssistantCreationOptions DeserializeAssistantCreationOptions(Jso string description = default; string instructions = default; IList tools = default; - IList fileIds = default; + CreateToolResourcesOptions toolResources = default; + float? temperature = default; + float? topP = default; + BinaryData responseFormat = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -200,18 +248,44 @@ internal static AssistantCreationOptions DeserializeAssistantCreationOptions(Jso tools = array; continue; } - if (property.NameEquals("file_ids"u8)) + if (property.NameEquals("tool_resources"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { + toolResources = null; continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + toolResources = CreateToolResourcesOptions.DeserializeCreateToolResourcesOptions(property.Value, options); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) { - array.Add(item.GetString()); + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; } - fileIds = array; + responseFormat = BinaryData.FromString(property.Value.GetRawText()); continue; } if (property.NameEquals("metadata"u8)) @@ -240,7 +314,10 @@ internal static AssistantCreationOptions DeserializeAssistantCreationOptions(Jso description, instructions, tools ?? new ChangeTrackingList(), - fileIds ?? new ChangeTrackingList(), + toolResources, + temperature, + topP, + responseFormat, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.cs index 34372f563399..87275c6b0976 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.cs @@ -54,7 +54,6 @@ public AssistantCreationOptions(string model) Model = model; Tools = new ChangeTrackingList(); - FileIds = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } @@ -66,19 +65,36 @@ public AssistantCreationOptions(string model) /// /// The collection of tools to enable for the new assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// - /// A list of previously uploaded file IDs to attach to the assistant. + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// The response format of the tool calls used by this assistant. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal AssistantCreationOptions(string model, string name, string description, string instructions, IList tools, IList fileIds, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal AssistantCreationOptions(string model, string name, string description, string instructions, IList tools, CreateToolResourcesOptions toolResources, float? temperature, float? topP, BinaryData responseFormat, IDictionary metadata, IDictionary serializedAdditionalRawData) { Model = model; Name = name; Description = description; Instructions = instructions; Tools = tools; - FileIds = fileIds; + ToolResources = toolResources; + Temperature = temperature; + TopP = topP; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -99,11 +115,71 @@ internal AssistantCreationOptions() /// /// The collection of tools to enable for the new assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IList Tools { get; } - /// A list of previously uploaded file IDs to attach to the assistant. - public IList FileIds { get; } + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + public CreateToolResourcesOptions ToolResources { get; set; } + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + public float? Temperature { get; set; } + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + public float? TopP { get; set; } + /// + /// The response format of the tool calls used by this assistant. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ResponseFormat { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantStreamEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantStreamEvent.cs new file mode 100644 index 000000000000..3c35b2590d78 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantStreamEvent.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// Each event in a server-sent events stream has an `event` and `data` property: + /// + /// ``` + /// event: thread.created + /// data: {"id": "thread_123", "object": "thread", ...} + /// ``` + /// + /// We emit events whenever a new object is created, transitions to a new state, or is being + /// streamed in parts (deltas). For example, we emit `thread.run.created` when a new run + /// is created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses + /// to create a message during a run, we emit a `thread.message.created event`, a + /// `thread.message.in_progress` event, many `thread.message.delta` events, and finally a + /// `thread.message.completed` event. + /// + /// We may add additional events over time, so we recommend handling unknown events gracefully + /// in your code. + /// + public readonly partial struct AssistantStreamEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AssistantStreamEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadCreatedValue = "thread.created"; + private const string ThreadRunCreatedValue = "thread.run.created"; + private const string ThreadRunQueuedValue = "thread.run.queued"; + private const string ThreadRunInProgressValue = "thread.run.in_progress"; + private const string ThreadRunRequiresActionValue = "thread.run.requires_action"; + private const string ThreadRunCompletedValue = "thread.run.completed"; + private const string ThreadRunFailedValue = "thread.run.failed"; + private const string ThreadRunCancellingValue = "thread.run.cancelling"; + private const string ThreadRunCancelledValue = "thread.run.cancelled"; + private const string ThreadRunExpiredValue = "thread.run.expired"; + private const string ThreadRunStepCreatedValue = "thread.run.step.created"; + private const string ThreadRunStepInProgressValue = "thread.run.step.in_progress"; + private const string ThreadRunStepDeltaValue = "thread.run.step.delta"; + private const string ThreadRunStepCompletedValue = "thread.run.step.completed"; + private const string ThreadRunStepFailedValue = "thread.run.step.failed"; + private const string ThreadRunStepCancelledValue = "thread.run.step.cancelled"; + private const string ThreadRunStepExpiredValue = "thread.run.step.expired"; + private const string ThreadMessageCreatedValue = "thread.message.created"; + private const string ThreadMessageInProgressValue = "thread.message.in_progress"; + private const string ThreadMessageDeltaValue = "thread.message.delta"; + private const string ThreadMessageCompletedValue = "thread.message.completed"; + private const string ThreadMessageIncompleteValue = "thread.message.incomplete"; + private const string ErrorValue = "error"; + private const string DoneValue = "done"; + + /// Event sent when a new thread is created. The data of this event is of type AssistantThread. + public static AssistantStreamEvent ThreadCreated { get; } = new AssistantStreamEvent(ThreadCreatedValue); + /// Event sent when a new run is created. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunCreated { get; } = new AssistantStreamEvent(ThreadRunCreatedValue); + /// Event sent when a run moves to `queued` status. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunQueued { get; } = new AssistantStreamEvent(ThreadRunQueuedValue); + /// Event sent when a run moves to `in_progress` status. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunInProgress { get; } = new AssistantStreamEvent(ThreadRunInProgressValue); + /// Event sent when a run moves to `requires_action` status. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunRequiresAction { get; } = new AssistantStreamEvent(ThreadRunRequiresActionValue); + /// Event sent when a run is completed. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunCompleted { get; } = new AssistantStreamEvent(ThreadRunCompletedValue); + /// Event sent when a run fails. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunFailed { get; } = new AssistantStreamEvent(ThreadRunFailedValue); + /// Event sent when a run moves to `cancelling` status. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunCancelling { get; } = new AssistantStreamEvent(ThreadRunCancellingValue); + /// Event sent when a run is cancelled. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunCancelled { get; } = new AssistantStreamEvent(ThreadRunCancelledValue); + /// Event sent when a run is expired. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunExpired { get; } = new AssistantStreamEvent(ThreadRunExpiredValue); + /// Event sent when a new thread run step is created. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepCreated { get; } = new AssistantStreamEvent(ThreadRunStepCreatedValue); + /// Event sent when a run step moves to `in_progress` status. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepInProgress { get; } = new AssistantStreamEvent(ThreadRunStepInProgressValue); + /// Event sent when a run stepis being streamed. The data of this event is of type RunStepDeltaChunk. + public static AssistantStreamEvent ThreadRunStepDelta { get; } = new AssistantStreamEvent(ThreadRunStepDeltaValue); + /// Event sent when a run step is completed. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepCompleted { get; } = new AssistantStreamEvent(ThreadRunStepCompletedValue); + /// Event sent when a run step fails. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepFailed { get; } = new AssistantStreamEvent(ThreadRunStepFailedValue); + /// Event sent when a run step is cancelled. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepCancelled { get; } = new AssistantStreamEvent(ThreadRunStepCancelledValue); + /// Event sent when a run step is expired. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepExpired { get; } = new AssistantStreamEvent(ThreadRunStepExpiredValue); + /// Event sent when a new message is created. The data of this event is of type ThreadMessage. + public static AssistantStreamEvent ThreadMessageCreated { get; } = new AssistantStreamEvent(ThreadMessageCreatedValue); + /// Event sent when a message moves to `in_progress` status. The data of this event is of type ThreadMessage. + public static AssistantStreamEvent ThreadMessageInProgress { get; } = new AssistantStreamEvent(ThreadMessageInProgressValue); + /// Event sent when a message is being streamed. The data of this event is of type MessageDeltaChunk. + public static AssistantStreamEvent ThreadMessageDelta { get; } = new AssistantStreamEvent(ThreadMessageDeltaValue); + /// Event sent when a message is completed. The data of this event is of type ThreadMessage. + public static AssistantStreamEvent ThreadMessageCompleted { get; } = new AssistantStreamEvent(ThreadMessageCompletedValue); + /// Event sent before a message is completed. The data of this event is of type ThreadMessage. + public static AssistantStreamEvent ThreadMessageIncomplete { get; } = new AssistantStreamEvent(ThreadMessageIncompleteValue); + /// Event sent when an error occurs, such as an internal server error or a timeout. + public static AssistantStreamEvent Error { get; } = new AssistantStreamEvent(ErrorValue); + /// Event sent when the stream is done. + public static AssistantStreamEvent Done { get; } = new AssistantStreamEvent(DoneValue); + /// Determines if two values are the same. + public static bool operator ==(AssistantStreamEvent left, AssistantStreamEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AssistantStreamEvent left, AssistantStreamEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AssistantStreamEvent(string value) => new AssistantStreamEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AssistantStreamEvent other && Equals(other); + /// + public bool Equals(AssistantStreamEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.Serialization.cs index 72793c7f2950..550ab46b2be4 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.Serialization.cs @@ -32,6 +32,15 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterO writer.WriteStringValue(Object); writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -88,6 +97,7 @@ internal static AssistantThread DeserializeAssistantThread(JsonElement element, string id = default; string @object = default; DateTimeOffset createdAt = default; + ToolResources toolResources = default; IReadOnlyDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -108,6 +118,16 @@ internal static AssistantThread DeserializeAssistantThread(JsonElement element, createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); continue; } + if (property.NameEquals("tool_resources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolResources = null; + continue; + } + toolResources = ToolResources.DeserializeToolResources(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -129,7 +149,13 @@ internal static AssistantThread DeserializeAssistantThread(JsonElement element, } } serializedAdditionalRawData = rawDataDictionary; - return new AssistantThread(id, @object, createdAt, metadata, serializedAdditionalRawData); + return new AssistantThread( + id, + @object, + createdAt, + toolResources, + metadata, + serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.cs index 55fb2ac9a88e..11820b0ed0b6 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.cs @@ -48,14 +48,20 @@ public partial class AssistantThread /// Initializes a new instance of . /// The identifier, which can be referenced in API endpoints. /// The Unix timestamp, in seconds, representing when this object was created. + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type + /// of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list + /// of vector store IDs. + /// /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// is null. - internal AssistantThread(string id, DateTimeOffset createdAt, IReadOnlyDictionary metadata) + internal AssistantThread(string id, DateTimeOffset createdAt, ToolResources toolResources, IReadOnlyDictionary metadata) { Argument.AssertNotNull(id, nameof(id)); Id = id; CreatedAt = createdAt; + ToolResources = toolResources; Metadata = metadata; } @@ -63,13 +69,19 @@ internal AssistantThread(string id, DateTimeOffset createdAt, IReadOnlyDictionar /// The identifier, which can be referenced in API endpoints. /// The object type, which is always 'thread'. /// The Unix timestamp, in seconds, representing when this object was created. + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type + /// of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list + /// of vector store IDs. + /// /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal AssistantThread(string id, string @object, DateTimeOffset createdAt, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal AssistantThread(string id, string @object, DateTimeOffset createdAt, ToolResources toolResources, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; CreatedAt = createdAt; + ToolResources = toolResources; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -84,6 +96,12 @@ internal AssistantThread() /// The Unix timestamp, in seconds, representing when this object was created. public DateTimeOffset CreatedAt { get; } + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type + /// of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list + /// of vector store IDs. + /// + public ToolResources ToolResources { get; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IReadOnlyDictionary Metadata { get; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.Serialization.cs index ffd998161e30..873de1490d7f 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.Serialization.cs @@ -36,6 +36,18 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mod } writer.WriteEndArray(); } + if (Optional.IsDefined(ToolResources)) + { + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } + } if (Optional.IsCollectionDefined(Metadata)) { if (Metadata != null) @@ -92,7 +104,8 @@ internal static AssistantThreadCreationOptions DeserializeAssistantThreadCreatio { return null; } - IList messages = default; + IList messages = default; + CreateToolResourcesOptions toolResources = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -104,14 +117,24 @@ internal static AssistantThreadCreationOptions DeserializeAssistantThreadCreatio { continue; } - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(ThreadInitializationMessage.DeserializeThreadInitializationMessage(item, options)); + array.Add(ThreadMessageOptions.DeserializeThreadMessageOptions(item, options)); } messages = array; continue; } + if (property.NameEquals("tool_resources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolResources = null; + continue; + } + toolResources = CreateToolResourcesOptions.DeserializeCreateToolResourcesOptions(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -132,7 +155,7 @@ internal static AssistantThreadCreationOptions DeserializeAssistantThreadCreatio } } serializedAdditionalRawData = rawDataDictionary; - return new AssistantThreadCreationOptions(messages ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new AssistantThreadCreationOptions(messages ?? new ChangeTrackingList(), toolResources, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.cs index 2df216a2c7e8..086af4d9dc8a 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.cs @@ -48,23 +48,35 @@ public partial class AssistantThreadCreationOptions /// Initializes a new instance of . public AssistantThreadCreationOptions() { - Messages = new ChangeTrackingList(); + Messages = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } /// Initializes a new instance of . /// The initial messages to associate with the new thread. + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the + /// type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires + /// a list of vector store IDs. + /// /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal AssistantThreadCreationOptions(IList messages, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal AssistantThreadCreationOptions(IList messages, CreateToolResourcesOptions toolResources, IDictionary metadata, IDictionary serializedAdditionalRawData) { Messages = messages; + ToolResources = toolResources; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } /// The initial messages to associate with the new thread. - public IList Messages { get; } + public IList Messages { get; } + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the + /// type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires + /// a list of vector store IDs. + /// + public CreateToolResourcesOptions ToolResources { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.Serialization.cs new file mode 100644 index 000000000000..c1cc832cf7b1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class AssistantsApiResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AssistantsApiResponseFormat)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Type)) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.Value.ToString()); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AssistantsApiResponseFormat 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(AssistantsApiResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAssistantsApiResponseFormat(document.RootElement, options); + } + + internal static AssistantsApiResponseFormat DeserializeAssistantsApiResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ApiResponseFormat? type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + type = new ApiResponseFormat(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AssistantsApiResponseFormat(type, serializedAdditionalRawData); + } + + 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(AssistantsApiResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + AssistantsApiResponseFormat 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 DeserializeAssistantsApiResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AssistantsApiResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAssistantsApiResponseFormat(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatErrorResponse.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.cs similarity index 61% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatErrorResponse.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.cs index 767fce2b029e..02f2e275e525 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatErrorResponse.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -5,10 +8,13 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI +namespace Azure.AI.OpenAI.Assistants { - /// A structured representation of an error an Azure OpenAI request. - internal partial class AzureOpenAIChatErrorResponse + /// + /// An object describing the expected output of the model. If `json_object` only `function` type `tools` are allowed to be passed to the Run. + /// If `text` the model can return text or any value needed. + /// + public partial class AssistantsApiResponseFormat { /// /// Keeps track of any properties unknown to the library. @@ -40,22 +46,23 @@ internal partial class AzureOpenAIChatErrorResponse /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal AzureOpenAIChatErrorResponse() + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public AssistantsApiResponseFormat() { } - /// Initializes a new instance of . - /// + /// Initializes a new instance of . + /// Must be one of `text` or `json_object`. /// Keeps track of any properties unknown to the library. - internal AzureOpenAIChatErrorResponse(AzureOpenAIChatError error, IDictionary serializedAdditionalRawData) + internal AssistantsApiResponseFormat(ApiResponseFormat? type, IDictionary serializedAdditionalRawData) { - Error = error; - SerializedAdditionalRawData = serializedAdditionalRawData; + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Gets the error. - public AzureOpenAIChatError Error { get; } + /// Must be one of `text` or `json_object`. + public ApiResponseFormat? Type { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatMode.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatMode.cs new file mode 100644 index 000000000000..1dac794d9529 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatMode.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the mode in which the model will handle the return format of a tool call. + public readonly partial struct AssistantsApiResponseFormatMode : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AssistantsApiResponseFormatMode(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string NoneValue = "none"; + + /// Default value. Let the model handle the return format. + public static AssistantsApiResponseFormatMode Auto { get; } = new AssistantsApiResponseFormatMode(AutoValue); + /// Setting the value to `none`, will result in a 400 Bad request. + public static AssistantsApiResponseFormatMode None { get; } = new AssistantsApiResponseFormatMode(NoneValue); + /// Determines if two values are the same. + public static bool operator ==(AssistantsApiResponseFormatMode left, AssistantsApiResponseFormatMode right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AssistantsApiResponseFormatMode left, AssistantsApiResponseFormatMode right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AssistantsApiResponseFormatMode(string value) => new AssistantsApiResponseFormatMode(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AssistantsApiResponseFormatMode other && Equals(other); + /// + public bool Equals(AssistantsApiResponseFormatMode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiToolChoiceOptionMode.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiToolChoiceOptionMode.cs new file mode 100644 index 000000000000..89f7812a7ae0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiToolChoiceOptionMode.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Specifies how the tool choice will be used. + public readonly partial struct AssistantsApiToolChoiceOptionMode : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AssistantsApiToolChoiceOptionMode(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NoneValue = "none"; + private const string AutoValue = "auto"; + + /// The model will not call a function and instead generates a message. + public static AssistantsApiToolChoiceOptionMode None { get; } = new AssistantsApiToolChoiceOptionMode(NoneValue); + /// The model can pick between generating a message or calling a function. + public static AssistantsApiToolChoiceOptionMode Auto { get; } = new AssistantsApiToolChoiceOptionMode(AutoValue); + /// Determines if two values are the same. + public static bool operator ==(AssistantsApiToolChoiceOptionMode left, AssistantsApiToolChoiceOptionMode right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AssistantsApiToolChoiceOptionMode left, AssistantsApiToolChoiceOptionMode right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AssistantsApiToolChoiceOptionMode(string value) => new AssistantsApiToolChoiceOptionMode(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AssistantsApiToolChoiceOptionMode other && Equals(other); + /// + public bool Equals(AssistantsApiToolChoiceOptionMode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClient.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClient.cs index c85db38a83b6..996e52afcb6e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClient.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClient.cs @@ -39,7 +39,7 @@ protected AssistantsClient() } /// Creates a new assistant. - /// Body parameter. + /// The request details to use when creating a new assistant. /// The cancellation token to use. /// is null. public virtual async Task> CreateAssistantAsync(AssistantCreationOptions body, CancellationToken cancellationToken = default) @@ -53,7 +53,7 @@ public virtual async Task> CreateAssistantAsync(AssistantCre } /// Creates a new assistant. - /// Body parameter. + /// The request details to use when creating a new assistant. /// The cancellation token to use. /// is null. public virtual Response CreateAssistant(AssistantCreationOptions body, CancellationToken cancellationToken = default) @@ -332,7 +332,7 @@ internal virtual Response GetAssistant(string assistantId, RequestContext contex /// Modifies an existing assistant. /// The ID of the assistant to modify. - /// Body parameter. + /// The request details to use when modifying an existing assistant. /// The cancellation token to use. /// or is null. /// is an empty string, and was expected to be non-empty. @@ -349,7 +349,7 @@ public virtual async Task> UpdateAssistantAsync(string assis /// Modifies an existing assistant. /// The ID of the assistant to modify. - /// Body parameter. + /// The request details to use when modifying an existing assistant. /// The cancellation token to use. /// or is null. /// is an empty string, and was expected to be non-empty. @@ -542,42 +542,36 @@ internal virtual Response InternalDeleteAssistant(string assistantId, RequestCon } } - /// Attaches a previously uploaded file to an assistant for use by tools that can read files. - /// The ID of the assistant to attach the file to. - /// The ID of the previously uploaded file to attach. + /// Creates a new thread. Threads contain messages and can be run by assistants. + /// The details used to create a new assistant thread. /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public virtual async Task> LinkAssistantFileAsync(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// is null. + public virtual async Task> CreateThreadAsync(AssistantThreadCreationOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNull(fileId, nameof(fileId)); + Argument.AssertNotNull(body, nameof(body)); - CreateAssistantFileRequest createAssistantFileRequest = new CreateAssistantFileRequest(fileId, null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await LinkAssistantFileAsync(assistantId, createAssistantFileRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(AssistantFile.FromResponse(response), response); + Response response = await CreateThreadAsync(content, context).ConfigureAwait(false); + return Response.FromValue(AssistantThread.FromResponse(response), response); } - /// Attaches a previously uploaded file to an assistant for use by tools that can read files. - /// The ID of the assistant to attach the file to. - /// The ID of the previously uploaded file to attach. + /// Creates a new thread. Threads contain messages and can be run by assistants. + /// The details used to create a new assistant thread. /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public virtual Response LinkAssistantFile(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// is null. + public virtual Response CreateThread(AssistantThreadCreationOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNull(fileId, nameof(fileId)); + Argument.AssertNotNull(body, nameof(body)); - CreateAssistantFileRequest createAssistantFileRequest = new CreateAssistantFileRequest(fileId, null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = LinkAssistantFile(assistantId, createAssistantFileRequest.ToRequestContent(), context); - return Response.FromValue(AssistantFile.FromResponse(response), response); + Response response = CreateThread(content, context); + return Response.FromValue(AssistantThread.FromResponse(response), response); } /// - /// [Protocol Method] Attaches a previously uploaded file to an assistant for use by tools that can read files. + /// [Protocol Method] Creates a new thread. Threads contain messages and can be run by assistants. /// /// /// @@ -586,23 +580,20 @@ public virtual Response LinkAssistantFile(string assistantId, str /// /// /// - /// The ID of the assistant to attach the file to. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task LinkAssistantFileAsync(string assistantId, RequestContent content, RequestContext context = null) + internal virtual async Task CreateThreadAsync(RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.LinkAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThread"); scope.Start(); try { - using HttpMessage message = CreateLinkAssistantFileRequest(assistantId, content, context); + using HttpMessage message = CreateCreateThreadRequest(content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -613,7 +604,7 @@ internal virtual async Task LinkAssistantFileAsync(string assistantId, } /// - /// [Protocol Method] Attaches a previously uploaded file to an assistant for use by tools that can read files. + /// [Protocol Method] Creates a new thread. Threads contain messages and can be run by assistants. /// /// /// @@ -622,23 +613,20 @@ internal virtual async Task LinkAssistantFileAsync(string assistantId, /// /// /// - /// The ID of the assistant to attach the file to. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response LinkAssistantFile(string assistantId, RequestContent content, RequestContext context = null) + internal virtual Response CreateThread(RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.LinkAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThread"); scope.Start(); try { - using HttpMessage message = CreateLinkAssistantFileRequest(assistantId, content, context); + using HttpMessage message = CreateCreateThreadRequest(content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -648,76 +636,59 @@ internal virtual Response LinkAssistantFile(string assistantId, RequestContent c } } - /// Gets a list of files attached to a specific assistant, as used by tools that can read files. - /// The ID of the assistant to retrieve the list of attached files for. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Gets information about an existing thread. + /// The ID of the thread to retrieve information about. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalGetAssistantFilesAsync(string assistantId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetThreadAsync(string threadId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalGetAssistantFilesAsync(assistantId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); - return Response.FromValue(InternalOpenAIPageableListOfAssistantFile.FromResponse(response), response); + Response response = await GetThreadAsync(threadId, context).ConfigureAwait(false); + return Response.FromValue(AssistantThread.FromResponse(response), response); } - /// Gets a list of files attached to a specific assistant, as used by tools that can read files. - /// The ID of the assistant to retrieve the list of attached files for. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Gets information about an existing thread. + /// The ID of the thread to retrieve information about. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual Response InternalGetAssistantFiles(string assistantId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetThread(string threadId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalGetAssistantFiles(assistantId, limit, order?.ToString(), after, before, context); - return Response.FromValue(InternalOpenAIPageableListOfAssistantFile.FromResponse(response), response); + Response response = GetThread(threadId, context); + return Response.FromValue(AssistantThread.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of files attached to a specific assistant, as used by tools that can read files. + /// [Protocol Method] Gets information about an existing thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the assistant to retrieve the list of attached files for. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the thread to retrieve information about. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalGetAssistantFilesAsync(string assistantId, int? limit, string order, string after, string before, RequestContext context) + internal virtual async Task GetThreadAsync(string threadId, RequestContext context) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetAssistantFiles"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetThread"); scope.Start(); try { - using HttpMessage message = CreateInternalGetAssistantFilesRequest(assistantId, limit, order, after, before, context); + using HttpMessage message = CreateGetThreadRequest(threadId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -728,39 +699,30 @@ internal virtual async Task InternalGetAssistantFilesAsync(string assi } /// - /// [Protocol Method] Gets a list of files attached to a specific assistant, as used by tools that can read files. + /// [Protocol Method] Gets information about an existing thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the assistant to retrieve the list of attached files for. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the thread to retrieve information about. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalGetAssistantFiles(string assistantId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response GetThread(string threadId, RequestContext context) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetAssistantFiles"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetThread"); scope.Start(); try { - using HttpMessage message = CreateInternalGetAssistantFilesRequest(assistantId, limit, order, after, before, context); + using HttpMessage message = CreateGetThreadRequest(threadId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -770,40 +732,42 @@ internal virtual Response InternalGetAssistantFiles(string assistantId, int? lim } } - /// Retrieves a file attached to an assistant. - /// The ID of the assistant associated with the attached file. - /// The ID of the file to retrieve. + /// Modifies an existing thread. + /// The ID of the thread to modify. + /// The details used to update an existing assistant thread. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> GetAssistantFileAsync(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> UpdateThreadAsync(string threadId, UpdateAssistantThreadOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNull(body, nameof(body)); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetAssistantFileAsync(assistantId, fileId, context).ConfigureAwait(false); - return Response.FromValue(AssistantFile.FromResponse(response), response); + Response response = await UpdateThreadAsync(threadId, content, context).ConfigureAwait(false); + return Response.FromValue(AssistantThread.FromResponse(response), response); } - /// Retrieves a file attached to an assistant. - /// The ID of the assistant associated with the attached file. - /// The ID of the file to retrieve. + /// Modifies an existing thread. + /// The ID of the thread to modify. + /// The details used to update an existing assistant thread. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response GetAssistantFile(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response UpdateThread(string threadId, UpdateAssistantThreadOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNull(body, nameof(body)); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetAssistantFile(assistantId, fileId, context); - return Response.FromValue(AssistantFile.FromResponse(response), response); + Response response = UpdateThread(threadId, content, context); + return Response.FromValue(AssistantThread.FromResponse(response), response); } /// - /// [Protocol Method] Retrieves a file attached to an assistant. + /// [Protocol Method] Modifies an existing thread. /// /// /// @@ -812,23 +776,23 @@ public virtual Response GetAssistantFile(string assistantId, stri /// /// /// - /// The ID of the assistant associated with the attached file. - /// The ID of the file to retrieve. + /// The ID of the thread to modify. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetAssistantFileAsync(string assistantId, string fileId, RequestContext context) + internal virtual async Task UpdateThreadAsync(string threadId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateThread"); scope.Start(); try { - using HttpMessage message = CreateGetAssistantFileRequest(assistantId, fileId, context); + using HttpMessage message = CreateUpdateThreadRequest(threadId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -839,7 +803,7 @@ internal virtual async Task GetAssistantFileAsync(string assistantId, } /// - /// [Protocol Method] Retrieves a file attached to an assistant. + /// [Protocol Method] Modifies an existing thread. /// /// /// @@ -848,23 +812,23 @@ internal virtual async Task GetAssistantFileAsync(string assistantId, /// /// /// - /// The ID of the assistant associated with the attached file. - /// The ID of the file to retrieve. + /// The ID of the thread to modify. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetAssistantFile(string assistantId, string fileId, RequestContext context) + internal virtual Response UpdateThread(string threadId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateThread"); scope.Start(); try { - using HttpMessage message = CreateGetAssistantFileRequest(assistantId, fileId, context); + using HttpMessage message = CreateUpdateThreadRequest(threadId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -874,47 +838,36 @@ internal virtual Response GetAssistantFile(string assistantId, string fileId, Re } } - /// - /// Unlinks a previously attached file from an assistant, rendering it unavailable for use by tools that can read - /// files. - /// - /// The ID of the assistant from which the specified file should be unlinked. - /// The ID of the file to unlink from the specified assistant. + /// Deletes an existing thread. + /// The ID of the thread to delete. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalUnlinkAssistantFileAsync(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + internal virtual async Task> InternalDeleteThreadAsync(string threadId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalUnlinkAssistantFileAsync(assistantId, fileId, context).ConfigureAwait(false); - return Response.FromValue(InternalAssistantFileDeletionStatus.FromResponse(response), response); + Response response = await InternalDeleteThreadAsync(threadId, context).ConfigureAwait(false); + return Response.FromValue(ThreadDeletionStatus.FromResponse(response), response); } - /// - /// Unlinks a previously attached file from an assistant, rendering it unavailable for use by tools that can read - /// files. - /// - /// The ID of the assistant from which the specified file should be unlinked. - /// The ID of the file to unlink from the specified assistant. + /// Deletes an existing thread. + /// The ID of the thread to delete. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual Response InternalUnlinkAssistantFile(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + internal virtual Response InternalDeleteThread(string threadId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalUnlinkAssistantFile(assistantId, fileId, context); - return Response.FromValue(InternalAssistantFileDeletionStatus.FromResponse(response), response); + Response response = InternalDeleteThread(threadId, context); + return Response.FromValue(ThreadDeletionStatus.FromResponse(response), response); } /// - /// [Protocol Method] Unlinks a previously attached file from an assistant, rendering it unavailable for use by tools that can read - /// files. + /// [Protocol Method] Deletes an existing thread. /// /// /// @@ -923,28 +876,26 @@ internal virtual Response InternalUnlinkAss /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the assistant from which the specified file should be unlinked. - /// The ID of the file to unlink from the specified assistant. + /// The ID of the thread to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalUnlinkAssistantFileAsync(string assistantId, string fileId, RequestContext context) + internal virtual async Task InternalDeleteThreadAsync(string threadId, RequestContext context) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalUnlinkAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteThread"); scope.Start(); try { - using HttpMessage message = CreateInternalUnlinkAssistantFileRequest(assistantId, fileId, context); + using HttpMessage message = CreateInternalDeleteThreadRequest(threadId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -955,8 +906,7 @@ internal virtual async Task InternalUnlinkAssistantFileAsync(string as } /// - /// [Protocol Method] Unlinks a previously attached file from an assistant, rendering it unavailable for use by tools that can read - /// files. + /// [Protocol Method] Deletes an existing thread. /// /// /// @@ -965,28 +915,26 @@ internal virtual async Task InternalUnlinkAssistantFileAsync(string as /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the assistant from which the specified file should be unlinked. - /// The ID of the file to unlink from the specified assistant. + /// The ID of the thread to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalUnlinkAssistantFile(string assistantId, string fileId, RequestContext context) + internal virtual Response InternalDeleteThread(string threadId, RequestContext context) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalUnlinkAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteThread"); scope.Start(); try { - using HttpMessage message = CreateInternalUnlinkAssistantFileRequest(assistantId, fileId, context); + using HttpMessage message = CreateInternalDeleteThreadRequest(threadId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -996,36 +944,42 @@ internal virtual Response InternalUnlinkAssistantFile(string assistantId, string } } - /// Creates a new thread. Threads contain messages and can be run by assistants. - /// Body parameter. + /// Creates a new message on a specified thread. + /// The ID of the thread to create the new message on. + /// A single message within an assistant thread, as provided during that thread's creation for its initial state. /// The cancellation token to use. - /// is null. - public virtual async Task> CreateThreadAsync(AssistantThreadCreationOptions body, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CreateMessageAsync(string threadId, ThreadMessageOptions body, CancellationToken cancellationToken = default) { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(body, nameof(body)); using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateThreadAsync(content, context).ConfigureAwait(false); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = await CreateMessageAsync(threadId, content, context).ConfigureAwait(false); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } - /// Creates a new thread. Threads contain messages and can be run by assistants. - /// Body parameter. + /// Creates a new message on a specified thread. + /// The ID of the thread to create the new message on. + /// A single message within an assistant thread, as provided during that thread's creation for its initial state. /// The cancellation token to use. - /// is null. - public virtual Response CreateThread(AssistantThreadCreationOptions body, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CreateMessage(string threadId, ThreadMessageOptions body, CancellationToken cancellationToken = default) { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(body, nameof(body)); using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateThread(content, context); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = CreateMessage(threadId, content, context); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } /// - /// [Protocol Method] Creates a new thread. Threads contain messages and can be run by assistants. + /// [Protocol Method] Creates a new message on a specified thread. /// /// /// @@ -1034,20 +988,23 @@ public virtual Response CreateThread(AssistantThreadCreationOpt /// /// /// + /// The ID of the thread to create the new message on. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task CreateThreadAsync(RequestContent content, RequestContext context = null) + internal virtual async Task CreateMessageAsync(string threadId, RequestContent content, RequestContext context = null) { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateMessage"); scope.Start(); try { - using HttpMessage message = CreateCreateThreadRequest(content, context); + using HttpMessage message = CreateCreateMessageRequest(threadId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1058,7 +1015,7 @@ internal virtual async Task CreateThreadAsync(RequestContent content, } /// - /// [Protocol Method] Creates a new thread. Threads contain messages and can be run by assistants. + /// [Protocol Method] Creates a new message on a specified thread. /// /// /// @@ -1067,20 +1024,23 @@ internal virtual async Task CreateThreadAsync(RequestContent content, /// /// /// + /// The ID of the thread to create the new message on. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response CreateThread(RequestContent content, RequestContext context = null) + internal virtual Response CreateMessage(string threadId, RequestContent content, RequestContext context = null) { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateMessage"); scope.Start(); try { - using HttpMessage message = CreateCreateThreadRequest(content, context); + using HttpMessage message = CreateCreateMessageRequest(threadId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1090,59 +1050,79 @@ internal virtual Response CreateThread(RequestContent content, RequestContext co } } - /// Gets information about an existing thread. - /// The ID of the thread to retrieve information about. + /// Gets a list of messages that exist on a thread. + /// The ID of the thread to list messages from. + /// Filter messages by the run ID that generated them. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - public virtual async Task> GetThreadAsync(string threadId, CancellationToken cancellationToken = default) + internal virtual async Task> InternalGetMessagesAsync(string threadId, string runId = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetThreadAsync(threadId, context).ConfigureAwait(false); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = await InternalGetMessagesAsync(threadId, runId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(InternalOpenAIPageableListOfThreadMessage.FromResponse(response), response); } - /// Gets information about an existing thread. - /// The ID of the thread to retrieve information about. + /// Gets a list of messages that exist on a thread. + /// The ID of the thread to list messages from. + /// Filter messages by the run ID that generated them. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - public virtual Response GetThread(string threadId, CancellationToken cancellationToken = default) + internal virtual Response InternalGetMessages(string threadId, string runId = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetThread(threadId, context); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = InternalGetMessages(threadId, runId, limit, order?.ToString(), after, before, context); + return Response.FromValue(InternalOpenAIPageableListOfThreadMessage.FromResponse(response), response); } /// - /// [Protocol Method] Gets information about an existing thread. + /// [Protocol Method] Gets a list of messages that exist on a thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// /// /// - /// The ID of the thread to retrieve information about. + /// The ID of the thread to list messages from. + /// Filter messages by the run ID that generated them. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetThreadAsync(string threadId, RequestContext context) + internal virtual async Task InternalGetMessagesAsync(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessages"); scope.Start(); try { - using HttpMessage message = CreateGetThreadRequest(threadId, context); + using HttpMessage message = CreateInternalGetMessagesRequest(threadId, runId, limit, order, after, before, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1153,30 +1133,40 @@ internal virtual async Task GetThreadAsync(string threadId, RequestCon } /// - /// [Protocol Method] Gets information about an existing thread. + /// [Protocol Method] Gets a list of messages that exist on a thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// /// /// - /// The ID of the thread to retrieve information about. + /// The ID of the thread to list messages from. + /// Filter messages by the run ID that generated them. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetThread(string threadId, RequestContext context) + internal virtual Response InternalGetMessages(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessages"); scope.Start(); try { - using HttpMessage message = CreateGetThreadRequest(threadId, context); + using HttpMessage message = CreateInternalGetMessagesRequest(threadId, runId, limit, order, after, before, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1186,40 +1176,40 @@ internal virtual Response GetThread(string threadId, RequestContext context) } } - /// Modifies an existing thread. - /// The ID of the thread to modify. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Gets an existing message from an existing thread. + /// The ID of the thread to retrieve the specified message from. + /// The ID of the message to retrieve from the specified thread. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual async Task> UpdateThreadAsync(string threadId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetMessageAsync(string threadId, string messageId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); - UpdateThreadRequest updateThreadRequest = new UpdateThreadRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await UpdateThreadAsync(threadId, updateThreadRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = await GetMessageAsync(threadId, messageId, context).ConfigureAwait(false); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } - /// Modifies an existing thread. - /// The ID of the thread to modify. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Gets an existing message from an existing thread. + /// The ID of the thread to retrieve the specified message from. + /// The ID of the message to retrieve from the specified thread. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual Response UpdateThread(string threadId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetMessage(string threadId, string messageId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); - UpdateThreadRequest updateThreadRequest = new UpdateThreadRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = UpdateThread(threadId, updateThreadRequest.ToRequestContent(), context); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = GetMessage(threadId, messageId, context); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } /// - /// [Protocol Method] Modifies an existing thread. + /// [Protocol Method] Gets an existing message from an existing thread. /// /// /// @@ -1228,23 +1218,23 @@ public virtual Response UpdateThread(string threadId, IReadOnly /// /// /// - /// The ID of the thread to modify. - /// The content to send as the body of the request. + /// The ID of the thread to retrieve the specified message from. + /// The ID of the message to retrieve from the specified thread. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task UpdateThreadAsync(string threadId, RequestContent content, RequestContext context = null) + internal virtual async Task GetMessageAsync(string threadId, string messageId, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessage"); scope.Start(); try { - using HttpMessage message = CreateUpdateThreadRequest(threadId, content, context); + using HttpMessage message = CreateGetMessageRequest(threadId, messageId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1255,7 +1245,7 @@ internal virtual async Task UpdateThreadAsync(string threadId, Request } /// - /// [Protocol Method] Modifies an existing thread. + /// [Protocol Method] Gets an existing message from an existing thread. /// /// /// @@ -1264,23 +1254,23 @@ internal virtual async Task UpdateThreadAsync(string threadId, Request /// /// /// - /// The ID of the thread to modify. - /// The content to send as the body of the request. + /// The ID of the thread to retrieve the specified message from. + /// The ID of the message to retrieve from the specified thread. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response UpdateThread(string threadId, RequestContent content, RequestContext context = null) + internal virtual Response GetMessage(string threadId, string messageId, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessage"); scope.Start(); try { - using HttpMessage message = CreateUpdateThreadRequest(threadId, content, context); + using HttpMessage message = CreateGetMessageRequest(threadId, messageId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1290,64 +1280,71 @@ internal virtual Response UpdateThread(string threadId, RequestContent content, } } - /// Deletes an existing thread. - /// The ID of the thread to delete. + /// Modifies an existing message on an existing thread. + /// The ID of the thread containing the specified message to modify. + /// The ID of the message to modify on the specified thread. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalDeleteThreadAsync(string threadId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> UpdateMessageAsync(string threadId, string messageId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + UpdateMessageRequest updateMessageRequest = new UpdateMessageRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalDeleteThreadAsync(threadId, context).ConfigureAwait(false); - return Response.FromValue(ThreadDeletionStatus.FromResponse(response), response); + Response response = await UpdateMessageAsync(threadId, messageId, updateMessageRequest.ToRequestContent(), context).ConfigureAwait(false); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } - /// Deletes an existing thread. - /// The ID of the thread to delete. + /// Modifies an existing message on an existing thread. + /// The ID of the thread containing the specified message to modify. + /// The ID of the message to modify on the specified thread. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual Response InternalDeleteThread(string threadId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response UpdateMessage(string threadId, string messageId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + UpdateMessageRequest updateMessageRequest = new UpdateMessageRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalDeleteThread(threadId, context); - return Response.FromValue(ThreadDeletionStatus.FromResponse(response), response); + Response response = UpdateMessage(threadId, messageId, updateMessageRequest.ToRequestContent(), context); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } /// - /// [Protocol Method] Deletes an existing thread. + /// [Protocol Method] Modifies an existing message on an existing thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread to delete. + /// The ID of the thread containing the specified message to modify. + /// The ID of the message to modify on the specified thread. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalDeleteThreadAsync(string threadId, RequestContext context) + internal virtual async Task UpdateMessageAsync(string threadId, string messageId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateMessage"); scope.Start(); try { - using HttpMessage message = CreateInternalDeleteThreadRequest(threadId, context); + using HttpMessage message = CreateUpdateMessageRequest(threadId, messageId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1358,35 +1355,34 @@ internal virtual async Task InternalDeleteThreadAsync(string threadId, } /// - /// [Protocol Method] Deletes an existing thread. + /// [Protocol Method] Modifies an existing message on an existing thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread to delete. + /// The ID of the thread containing the specified message to modify. + /// The ID of the message to modify on the specified thread. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalDeleteThread(string threadId, RequestContext context) + internal virtual Response UpdateMessage(string threadId, string messageId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateMessage"); scope.Start(); try { - using HttpMessage message = CreateInternalDeleteThreadRequest(threadId, context); + using HttpMessage message = CreateUpdateMessageRequest(threadId, messageId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1396,48 +1392,42 @@ internal virtual Response InternalDeleteThread(string threadId, RequestContext c } } - /// Creates a new message on a specified thread. - /// The ID of the thread to create the new message on. - /// The role to associate with the new message. - /// The textual content for the new message. - /// A list of up to 10 file IDs to associate with the message, as used by tools like 'code_interpreter' or 'retrieval' that can read files. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Creates a new run for an assistant thread. + /// The ID of the thread to run. + /// The details used when creating a new run of an assistant thread. /// The cancellation token to use. - /// or is null. + /// or is null. /// is an empty string, and was expected to be non-empty. - public virtual async Task> CreateMessageAsync(string threadId, MessageRole role, string content, IEnumerable fileIds = null, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + public virtual async Task> CreateRunAsync(string threadId, CreateRunOptions body, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNull(body, nameof(body)); - CreateMessageRequest createMessageRequest = new CreateMessageRequest(role, content, fileIds?.ToList() as IReadOnlyList ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateMessageAsync(threadId, createMessageRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = await CreateRunAsync(threadId, content, context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); } - /// Creates a new message on a specified thread. - /// The ID of the thread to create the new message on. - /// The role to associate with the new message. - /// The textual content for the new message. - /// A list of up to 10 file IDs to associate with the message, as used by tools like 'code_interpreter' or 'retrieval' that can read files. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Creates a new run for an assistant thread. + /// The ID of the thread to run. + /// The details used when creating a new run of an assistant thread. /// The cancellation token to use. - /// or is null. + /// or is null. /// is an empty string, and was expected to be non-empty. - public virtual Response CreateMessage(string threadId, MessageRole role, string content, IEnumerable fileIds = null, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + public virtual Response CreateRun(string threadId, CreateRunOptions body, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNull(body, nameof(body)); - CreateMessageRequest createMessageRequest = new CreateMessageRequest(role, content, fileIds?.ToList() as IReadOnlyList ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateMessage(threadId, createMessageRequest.ToRequestContent(), context); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = CreateRun(threadId, content, context); + return Response.FromValue(ThreadRun.FromResponse(response), response); } /// - /// [Protocol Method] Creates a new message on a specified thread. + /// [Protocol Method] Creates a new run for an assistant thread. /// /// /// @@ -1446,23 +1436,23 @@ public virtual Response CreateMessage(string threadId, MessageRol /// /// /// - /// The ID of the thread to create the new message on. + /// The ID of the thread to run. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// or is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task CreateMessageAsync(string threadId, RequestContent content, RequestContext context = null) + internal virtual async Task CreateRunAsync(string threadId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateRun"); scope.Start(); try { - using HttpMessage message = CreateCreateMessageRequest(threadId, content, context); + using HttpMessage message = CreateCreateRunRequest(threadId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1473,7 +1463,7 @@ internal virtual async Task CreateMessageAsync(string threadId, Reques } /// - /// [Protocol Method] Creates a new message on a specified thread. + /// [Protocol Method] Creates a new run for an assistant thread. /// /// /// @@ -1482,23 +1472,23 @@ internal virtual async Task CreateMessageAsync(string threadId, Reques /// /// /// - /// The ID of the thread to create the new message on. + /// The ID of the thread to run. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// or is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response CreateMessage(string threadId, RequestContent content, RequestContext context = null) + internal virtual Response CreateRun(string threadId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateRun"); scope.Start(); try { - using HttpMessage message = CreateCreateMessageRequest(threadId, content, context); + using HttpMessage message = CreateCreateRunRequest(threadId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1508,8 +1498,8 @@ internal virtual Response CreateMessage(string threadId, RequestContent content, } } - /// Gets a list of messages that exist on a thread. - /// The ID of the thread to list messages from. + /// Gets a list of runs for a specified thread. + /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. @@ -1517,17 +1507,17 @@ internal virtual Response CreateMessage(string threadId, RequestContent content, /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalGetMessagesAsync(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + internal virtual async Task> InternalGetRunsAsync(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalGetMessagesAsync(threadId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); - return Response.FromValue(InternalOpenAIPageableListOfThreadMessage.FromResponse(response), response); + Response response = await InternalGetRunsAsync(threadId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(InternalOpenAIPageableListOfThreadRun.FromResponse(response), response); } - /// Gets a list of messages that exist on a thread. - /// The ID of the thread to list messages from. + /// Gets a list of runs for a specified thread. + /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. @@ -1535,17 +1525,17 @@ internal virtual async Task> /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - internal virtual Response InternalGetMessages(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + internal virtual Response InternalGetRuns(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalGetMessages(threadId, limit, order?.ToString(), after, before, context); - return Response.FromValue(InternalOpenAIPageableListOfThreadMessage.FromResponse(response), response); + Response response = InternalGetRuns(threadId, limit, order?.ToString(), after, before, context); + return Response.FromValue(InternalOpenAIPageableListOfThreadRun.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of messages that exist on a thread. + /// [Protocol Method] Gets a list of runs for a specified thread. /// /// /// @@ -1554,12 +1544,12 @@ internal virtual Response InternalGet /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the thread to list messages from. + /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. @@ -1569,15 +1559,15 @@ internal virtual Response InternalGet /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalGetMessagesAsync(string threadId, int? limit, string order, string after, string before, RequestContext context) + internal virtual async Task InternalGetRunsAsync(string threadId, int? limit, string order, string after, string before, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessages"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRuns"); scope.Start(); try { - using HttpMessage message = CreateInternalGetMessagesRequest(threadId, limit, order, after, before, context); + using HttpMessage message = CreateInternalGetRunsRequest(threadId, limit, order, after, before, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1588,7 +1578,7 @@ internal virtual async Task InternalGetMessagesAsync(string threadId, } /// - /// [Protocol Method] Gets a list of messages that exist on a thread. + /// [Protocol Method] Gets a list of runs for a specified thread. /// /// /// @@ -1597,12 +1587,12 @@ internal virtual async Task InternalGetMessagesAsync(string threadId, /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the thread to list messages from. + /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. @@ -1612,15 +1602,15 @@ internal virtual async Task InternalGetMessagesAsync(string threadId, /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalGetMessages(string threadId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response InternalGetRuns(string threadId, int? limit, string order, string after, string before, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessages"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRuns"); scope.Start(); try { - using HttpMessage message = CreateInternalGetMessagesRequest(threadId, limit, order, after, before, context); + using HttpMessage message = CreateInternalGetRunsRequest(threadId, limit, order, after, before, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1630,40 +1620,40 @@ internal virtual Response InternalGetMessages(string threadId, int? limit, strin } } - /// Gets an existing message from an existing thread. - /// The ID of the thread to retrieve the specified message from. - /// The ID of the message to retrieve from the specified thread. + /// Gets an existing run from an existing thread. + /// The ID of the thread to retrieve run information from. + /// The ID of the thread to retrieve information about. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> GetMessageAsync(string threadId, string messageId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetRunAsync(string threadId, string runId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetMessageAsync(threadId, messageId, context).ConfigureAwait(false); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = await GetRunAsync(threadId, runId, context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); } - /// Gets an existing message from an existing thread. - /// The ID of the thread to retrieve the specified message from. - /// The ID of the message to retrieve from the specified thread. + /// Gets an existing run from an existing thread. + /// The ID of the thread to retrieve run information from. + /// The ID of the thread to retrieve information about. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response GetMessage(string threadId, string messageId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetRun(string threadId, string runId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetMessage(threadId, messageId, context); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = GetRun(threadId, runId, context); + return Response.FromValue(ThreadRun.FromResponse(response), response); } /// - /// [Protocol Method] Gets an existing message from an existing thread. + /// [Protocol Method] Gets an existing run from an existing thread. /// /// /// @@ -1672,23 +1662,23 @@ public virtual Response GetMessage(string threadId, string messag /// /// /// - /// The ID of the thread to retrieve the specified message from. - /// The ID of the message to retrieve from the specified thread. + /// The ID of the thread to retrieve run information from. + /// The ID of the thread to retrieve information about. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetMessageAsync(string threadId, string messageId, RequestContext context) + internal virtual async Task GetRunAsync(string threadId, string runId, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRun"); scope.Start(); try { - using HttpMessage message = CreateGetMessageRequest(threadId, messageId, context); + using HttpMessage message = CreateGetRunRequest(threadId, runId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1699,7 +1689,7 @@ internal virtual async Task GetMessageAsync(string threadId, string me } /// - /// [Protocol Method] Gets an existing message from an existing thread. + /// [Protocol Method] Gets an existing run from an existing thread. /// /// /// @@ -1708,23 +1698,23 @@ internal virtual async Task GetMessageAsync(string threadId, string me /// /// /// - /// The ID of the thread to retrieve the specified message from. - /// The ID of the message to retrieve from the specified thread. + /// The ID of the thread to retrieve run information from. + /// The ID of the thread to retrieve information about. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetMessage(string threadId, string messageId, RequestContext context) + internal virtual Response GetRun(string threadId, string runId, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRun"); scope.Start(); try { - using HttpMessage message = CreateGetMessageRequest(threadId, messageId, context); + using HttpMessage message = CreateGetRunRequest(threadId, runId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1734,44 +1724,44 @@ internal virtual Response GetMessage(string threadId, string messageId, RequestC } } - /// Modifies an existing message on an existing thread. - /// The ID of the thread containing the specified message to modify. - /// The ID of the message to modify on the specified thread. + /// Modifies an existing thread run. + /// The ID of the thread associated with the specified run. + /// The ID of the run to modify. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> UpdateMessageAsync(string threadId, string messageId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> UpdateRunAsync(string threadId, string runId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - UpdateMessageRequest updateMessageRequest = new UpdateMessageRequest(metadata ?? new ChangeTrackingDictionary(), null); + UpdateRunRequest updateRunRequest = new UpdateRunRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await UpdateMessageAsync(threadId, messageId, updateMessageRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = await UpdateRunAsync(threadId, runId, updateRunRequest.ToRequestContent(), context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); } - /// Modifies an existing message on an existing thread. - /// The ID of the thread containing the specified message to modify. - /// The ID of the message to modify on the specified thread. + /// Modifies an existing thread run. + /// The ID of the thread associated with the specified run. + /// The ID of the run to modify. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response UpdateMessage(string threadId, string messageId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response UpdateRun(string threadId, string runId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - UpdateMessageRequest updateMessageRequest = new UpdateMessageRequest(metadata ?? new ChangeTrackingDictionary(), null); + UpdateRunRequest updateRunRequest = new UpdateRunRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = UpdateMessage(threadId, messageId, updateMessageRequest.ToRequestContent(), context); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = UpdateRun(threadId, runId, updateRunRequest.ToRequestContent(), context); + return Response.FromValue(ThreadRun.FromResponse(response), response); } /// - /// [Protocol Method] Modifies an existing message on an existing thread. + /// [Protocol Method] Modifies an existing thread run. /// /// /// @@ -1780,25 +1770,25 @@ public virtual Response UpdateMessage(string threadId, string mes /// /// /// - /// The ID of the thread containing the specified message to modify. - /// The ID of the message to modify on the specified thread. + /// The ID of the thread associated with the specified run. + /// The ID of the run to modify. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task UpdateMessageAsync(string threadId, string messageId, RequestContent content, RequestContext context = null) + internal virtual async Task UpdateRunAsync(string threadId, string runId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateRun"); scope.Start(); try { - using HttpMessage message = CreateUpdateMessageRequest(threadId, messageId, content, context); + using HttpMessage message = CreateUpdateRunRequest(threadId, runId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1809,7 +1799,7 @@ internal virtual async Task UpdateMessageAsync(string threadId, string } /// - /// [Protocol Method] Modifies an existing message on an existing thread. + /// [Protocol Method] Modifies an existing thread run. /// /// /// @@ -1818,25 +1808,25 @@ internal virtual async Task UpdateMessageAsync(string threadId, string /// /// /// - /// The ID of the thread containing the specified message to modify. - /// The ID of the message to modify on the specified thread. + /// The ID of the thread associated with the specified run. + /// The ID of the run to modify. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response UpdateMessage(string threadId, string messageId, RequestContent content, RequestContext context = null) + internal virtual Response UpdateRun(string threadId, string runId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateRun"); scope.Start(); try { - using HttpMessage message = CreateUpdateMessageRequest(threadId, messageId, content, context); + using HttpMessage message = CreateUpdateRunRequest(threadId, runId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1846,82 +1836,812 @@ internal virtual Response UpdateMessage(string threadId, string messageId, Reque } } - /// Gets a list of previously uploaded files associated with a message from a thread. - /// The ID of the thread containing the message to list files from. - /// The ID of the message to list files from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// The ID of the thread that was run. + /// The ID of the run that requires tool outputs. + /// A list of tools for which the outputs are being submitted. + /// If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalGetMessageFilesAsync(string threadId, string messageId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> SubmitToolOutputsToRunAsync(string threadId, string runId, IEnumerable toolOutputs, bool? stream = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(toolOutputs, nameof(toolOutputs)); + SubmitToolOutputsToRunRequest submitToolOutputsToRunRequest = new SubmitToolOutputsToRunRequest(toolOutputs.ToList(), stream, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalGetMessageFilesAsync(threadId, messageId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); - return Response.FromValue(InternalOpenAIPageableListOfMessageFile.FromResponse(response), response); + Response response = await SubmitToolOutputsToRunAsync(threadId, runId, submitToolOutputsToRunRequest.ToRequestContent(), context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); } - /// Gets a list of previously uploaded files associated with a message from a thread. - /// The ID of the thread containing the message to list files from. - /// The ID of the message to list files from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// The ID of the thread that was run. + /// The ID of the run that requires tool outputs. + /// A list of tools for which the outputs are being submitted. + /// If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual Response InternalGetMessageFiles(string threadId, string messageId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response SubmitToolOutputsToRun(string threadId, string runId, IEnumerable toolOutputs, bool? stream = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(toolOutputs, nameof(toolOutputs)); + SubmitToolOutputsToRunRequest submitToolOutputsToRunRequest = new SubmitToolOutputsToRunRequest(toolOutputs.ToList(), stream, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalGetMessageFiles(threadId, messageId, limit, order?.ToString(), after, before, context); - return Response.FromValue(InternalOpenAIPageableListOfMessageFile.FromResponse(response), response); + Response response = SubmitToolOutputsToRun(threadId, runId, submitToolOutputsToRunRequest.ToRequestContent(), context); + return Response.FromValue(ThreadRun.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of previously uploaded files associated with a message from a thread. + /// [Protocol Method] Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the run that requires tool outputs. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task SubmitToolOutputsToRunAsync(string threadId, string runId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.SubmitToolOutputsToRun"); + scope.Start(); + try + { + using HttpMessage message = CreateSubmitToolOutputsToRunRequest(threadId, runId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// /// /// - /// The ID of the thread containing the message to list files from. - /// The ID of the message to list files from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the thread that was run. + /// The ID of the run that requires tool outputs. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalGetMessageFilesAsync(string threadId, string messageId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response SubmitToolOutputsToRun(string threadId, string runId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessageFiles"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.SubmitToolOutputsToRun"); scope.Start(); try { - using HttpMessage message = CreateInternalGetMessageFilesRequest(threadId, messageId, limit, order, after, before, context); + using HttpMessage message = CreateSubmitToolOutputsToRunRequest(threadId, runId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Cancels a run of an in progress thread. + /// The ID of the thread being run. + /// The ID of the run to cancel. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> CancelRunAsync(string threadId, string runId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CancelRunAsync(threadId, runId, context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); + } + + /// Cancels a run of an in progress thread. + /// The ID of the thread being run. + /// The ID of the run to cancel. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response CancelRun(string threadId, string runId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CancelRun(threadId, runId, context); + return Response.FromValue(ThreadRun.FromResponse(response), response); + } + + /// + /// [Protocol Method] Cancels a run of an in progress thread. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the thread being run. + /// The ID of the run to cancel. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CancelRunAsync(string threadId, string runId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelRunRequest(threadId, runId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Cancels a run of an in progress thread. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the thread being run. + /// The ID of the run to cancel. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CancelRun(string threadId, string runId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelRunRequest(threadId, runId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Creates a new assistant thread and immediately starts a run using that new thread. + /// The details used when creating and immediately running a new assistant thread. + /// The cancellation token to use. + /// is null. + public virtual async Task> CreateThreadAndRunAsync(CreateAndRunThreadOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateThreadAndRunAsync(content, context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); + } + + /// Creates a new assistant thread and immediately starts a run using that new thread. + /// The details used when creating and immediately running a new assistant thread. + /// The cancellation token to use. + /// is null. + public virtual Response CreateThreadAndRun(CreateAndRunThreadOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateThreadAndRun(content, context); + return Response.FromValue(ThreadRun.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates a new assistant thread and immediately starts a run using that new thread. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CreateThreadAndRunAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThreadAndRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateThreadAndRunRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates a new assistant thread and immediately starts a run using that new thread. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CreateThreadAndRun(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThreadAndRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateThreadAndRunRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets a single run step from a thread run. + /// The ID of the thread that was run. + /// The ID of the specific run to retrieve the step from. + /// The ID of the step to retrieve information about. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public virtual async Task> GetRunStepAsync(string threadId, string runId, string stepId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetRunStepAsync(threadId, runId, stepId, context).ConfigureAwait(false); + return Response.FromValue(RunStep.FromResponse(response), response); + } + + /// Gets a single run step from a thread run. + /// The ID of the thread that was run. + /// The ID of the specific run to retrieve the step from. + /// The ID of the step to retrieve information about. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public virtual Response GetRunStep(string threadId, string runId, string stepId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetRunStep(threadId, runId, stepId, context); + return Response.FromValue(RunStep.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets a single run step from a thread run. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the specific run to retrieve the step from. + /// The ID of the step to retrieve information about. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetRunStepAsync(string threadId, string runId, string stepId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRunStep"); + scope.Start(); + try + { + using HttpMessage message = CreateGetRunStepRequest(threadId, runId, stepId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a single run step from a thread run. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the specific run to retrieve the step from. + /// The ID of the step to retrieve information about. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetRunStep(string threadId, string runId, string stepId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRunStep"); + scope.Start(); + try + { + using HttpMessage message = CreateGetRunStepRequest(threadId, runId, stepId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets a list of run steps from a thread run. + /// The ID of the thread that was run. + /// The ID of the run to list steps from. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + internal virtual async Task> InternalGetRunStepsAsync(string threadId, string runId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await InternalGetRunStepsAsync(threadId, runId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(InternalOpenAIPageableListOfRunStep.FromResponse(response), response); + } + + /// Gets a list of run steps from a thread run. + /// The ID of the thread that was run. + /// The ID of the run to list steps from. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + internal virtual Response InternalGetRunSteps(string threadId, string runId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = InternalGetRunSteps(threadId, runId, limit, order?.ToString(), after, before, context); + return Response.FromValue(InternalOpenAIPageableListOfRunStep.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets a list of run steps from a thread run. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the run to list steps from. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task InternalGetRunStepsAsync(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRunSteps"); + scope.Start(); + try + { + using HttpMessage message = CreateInternalGetRunStepsRequest(threadId, runId, limit, order, after, before, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a list of run steps from a thread run. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the run to list steps from. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response InternalGetRunSteps(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRunSteps"); + scope.Start(); + try + { + using HttpMessage message = CreateInternalGetRunStepsRequest(threadId, runId, limit, order, after, before, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets a list of previously uploaded files. + /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// The cancellation token to use. + internal virtual async Task> InternalListFilesAsync(OpenAIFilePurpose? purpose = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await InternalListFilesAsync(purpose?.ToString(), context).ConfigureAwait(false); + return Response.FromValue(InternalFileListResponse.FromResponse(response), response); + } + + /// Gets a list of previously uploaded files. + /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// The cancellation token to use. + internal virtual Response InternalListFiles(OpenAIFilePurpose? purpose = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = InternalListFiles(purpose?.ToString(), context); + return Response.FromValue(InternalFileListResponse.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets a list of previously uploaded files. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output" | "batch" | "batch_output" | "vision". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task InternalListFilesAsync(string purpose, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalListFiles"); + scope.Start(); + try + { + using HttpMessage message = CreateInternalListFilesRequest(purpose, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a list of previously uploaded files. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output" | "batch" | "batch_output" | "vision". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response InternalListFiles(string purpose, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalListFiles"); + scope.Start(); + try + { + using HttpMessage message = CreateInternalListFilesRequest(purpose, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Uploads a file for use by other operations. + /// The file data (not filename) to upload. + /// The intended purpose of the file. + /// A filename to associate with the uploaded data. + /// The cancellation token to use. + /// is null. + public virtual async Task> UploadFileAsync(Stream data, OpenAIFilePurpose purpose, string filename = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + UploadFileRequest uploadFileRequest = new UploadFileRequest(data, purpose, filename, null); + using MultipartFormDataRequestContent content = uploadFileRequest.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await UploadFileAsync(content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// Uploads a file for use by other operations. + /// The file data (not filename) to upload. + /// The intended purpose of the file. + /// A filename to associate with the uploaded data. + /// The cancellation token to use. + /// is null. + public virtual Response UploadFile(Stream data, OpenAIFilePurpose purpose, string filename = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + UploadFileRequest uploadFileRequest = new UploadFileRequest(data, purpose, filename, null); + using MultipartFormDataRequestContent content = uploadFileRequest.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = UploadFile(content, content.ContentType, context); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// + /// [Protocol Method] Uploads a file for use by other operations. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task UploadFileAsync(RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UploadFile"); + scope.Start(); + try + { + using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Uploads a file for use by other operations. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response UploadFile(RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UploadFile"); + scope.Start(); + try + { + using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Delete a previously uploaded file. + /// The ID of the file to delete. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + internal virtual async Task> InternalDeleteFileAsync(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await InternalDeleteFileAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(InternalFileDeletionStatus.FromResponse(response), response); + } + + /// Delete a previously uploaded file. + /// The ID of the file to delete. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + internal virtual Response InternalDeleteFile(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = InternalDeleteFile(fileId, context); + return Response.FromValue(InternalFileDeletionStatus.FromResponse(response), response); + } + + /// + /// [Protocol Method] Delete a previously uploaded file. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The ID of the file to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task InternalDeleteFileAsync(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteFile"); + scope.Start(); + try + { + using HttpMessage message = CreateInternalDeleteFileRequest(fileId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1932,7 +2652,7 @@ internal virtual async Task InternalGetMessageFilesAsync(string thread } /// - /// [Protocol Method] Gets a list of previously uploaded files associated with a message from a thread. + /// [Protocol Method] Delete a previously uploaded file. /// /// /// @@ -1941,32 +2661,26 @@ internal virtual async Task InternalGetMessageFilesAsync(string thread /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the thread containing the message to list files from. - /// The ID of the message to list files from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the file to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalGetMessageFiles(string threadId, string messageId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response InternalDeleteFile(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessageFiles"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteFile"); scope.Start(); try { - using HttpMessage message = CreateInternalGetMessageFilesRequest(threadId, messageId, limit, order, after, before, context); + using HttpMessage message = CreateInternalDeleteFileRequest(fileId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1976,44 +2690,36 @@ internal virtual Response InternalGetMessageFiles(string threadId, string messag } } - /// Gets information about a file attachment to a message within a thread. - /// The ID of the thread containing the message to get information from. - /// The ID of the message to get information from. - /// The ID of the file to get information about. + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public virtual async Task> GetMessageFileAsync(string threadId, string messageId, string fileId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetFileAsync(string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetMessageFileAsync(threadId, messageId, fileId, context).ConfigureAwait(false); - return Response.FromValue(MessageFile.FromResponse(response), response); + Response response = await GetFileAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(OpenAIFile.FromResponse(response), response); } - /// Gets information about a file attachment to a message within a thread. - /// The ID of the thread containing the message to get information from. - /// The ID of the message to get information from. - /// The ID of the file to get information about. + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public virtual Response GetMessageFile(string threadId, string messageId, string fileId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetFile(string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetMessageFile(threadId, messageId, fileId, context); - return Response.FromValue(MessageFile.FromResponse(response), response); + Response response = GetFile(fileId, context); + return Response.FromValue(OpenAIFile.FromResponse(response), response); } /// - /// [Protocol Method] Gets information about a file attachment to a message within a thread. + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. /// /// /// @@ -2022,25 +2728,21 @@ public virtual Response GetMessageFile(string threadId, string mess /// /// /// - /// The ID of the thread containing the message to get information from. - /// The ID of the message to get information from. - /// The ID of the file to get information about. + /// The ID of the file to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetMessageFileAsync(string threadId, string messageId, string fileId, RequestContext context) + internal virtual async Task GetFileAsync(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessageFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFile"); scope.Start(); try { - using HttpMessage message = CreateGetMessageFileRequest(threadId, messageId, fileId, context); + using HttpMessage message = CreateGetFileRequest(fileId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2051,7 +2753,7 @@ internal virtual async Task GetMessageFileAsync(string threadId, strin } /// - /// [Protocol Method] Gets information about a file attachment to a message within a thread. + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. /// /// /// @@ -2060,25 +2762,21 @@ internal virtual async Task GetMessageFileAsync(string threadId, strin /// /// /// - /// The ID of the thread containing the message to get information from. - /// The ID of the message to get information from. - /// The ID of the file to get information about. + /// The ID of the file to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetMessageFile(string threadId, string messageId, string fileId, RequestContext context) + internal virtual Response GetFile(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessageFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFile"); scope.Start(); try { - using HttpMessage message = CreateGetMessageFileRequest(threadId, messageId, fileId, context); + using HttpMessage message = CreateGetFileRequest(fileId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2088,42 +2786,36 @@ internal virtual Response GetMessageFile(string threadId, string messageId, stri } } - /// Creates a new run for an assistant thread. - /// The ID of the thread to run. - /// The details for the run to create. + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public virtual async Task> CreateRunAsync(string threadId, CreateRunOptions createRunOptions, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetFileContentAsync(string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(createRunOptions, nameof(createRunOptions)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using RequestContent content = createRunOptions.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateRunAsync(threadId, content, context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await GetFileContentAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(response.Content, response); } - /// Creates a new run for an assistant thread. - /// The ID of the thread to run. - /// The details for the run to create. + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public virtual Response CreateRun(string threadId, CreateRunOptions createRunOptions, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetFileContent(string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(createRunOptions, nameof(createRunOptions)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using RequestContent content = createRunOptions.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateRun(threadId, content, context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = GetFileContent(fileId, context); + return Response.FromValue(response.Content, response); } /// - /// [Protocol Method] Creates a new run for an assistant thread. + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. /// /// /// @@ -2132,23 +2824,21 @@ public virtual Response CreateRun(string threadId, CreateRunOptions c /// /// /// - /// The ID of the thread to run. - /// The content to send as the body of the request. + /// The ID of the file to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task CreateRunAsync(string threadId, RequestContent content, RequestContext context = null) + internal virtual async Task GetFileContentAsync(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFileContent"); scope.Start(); try { - using HttpMessage message = CreateCreateRunRequest(threadId, content, context); + using HttpMessage message = CreateGetFileContentRequest(fileId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2159,7 +2849,7 @@ internal virtual async Task CreateRunAsync(string threadId, RequestCon } /// - /// [Protocol Method] Creates a new run for an assistant thread. + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. /// /// /// @@ -2168,23 +2858,21 @@ internal virtual async Task CreateRunAsync(string threadId, RequestCon /// /// /// - /// The ID of the thread to run. - /// The content to send as the body of the request. + /// The ID of the file to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response CreateRun(string threadId, RequestContent content, RequestContext context = null) + internal virtual Response GetFileContent(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFileContent"); scope.Start(); try { - using HttpMessage message = CreateCreateRunRequest(threadId, content, context); + using HttpMessage message = CreateGetFileContentRequest(fileId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2194,76 +2882,56 @@ internal virtual Response CreateRun(string threadId, RequestContent content, Req } } - /// Gets a list of runs for a specified thread. - /// The ID of the thread to list runs from. + /// Returns a list of vector stores. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalGetRunsAsync(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + public virtual async Task> GetVectorStoresAsync(int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalGetRunsAsync(threadId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); - return Response.FromValue(InternalOpenAIPageableListOfThreadRun.FromResponse(response), response); + Response response = await GetVectorStoresAsync(limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(OpenAIPageableListOfVectorStore.FromResponse(response), response); } - /// Gets a list of runs for a specified thread. - /// The ID of the thread to list runs from. + /// Returns a list of vector stores. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual Response InternalGetRuns(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + public virtual Response GetVectorStores(int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalGetRuns(threadId, limit, order?.ToString(), after, before, context); - return Response.FromValue(InternalOpenAIPageableListOfThreadRun.FromResponse(response), response); + Response response = GetVectorStores(limit, order?.ToString(), after, before, context); + return Response.FromValue(OpenAIPageableListOfVectorStore.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of runs for a specified thread. + /// [Protocol Method] Returns a list of vector stores. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalGetRunsAsync(string threadId, int? limit, string order, string after, string before, RequestContext context) + internal virtual async Task GetVectorStoresAsync(int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRuns"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStores"); scope.Start(); try { - using HttpMessage message = CreateInternalGetRunsRequest(threadId, limit, order, after, before, context); + using HttpMessage message = CreateGetVectorStoresRequest(limit, order, after, before, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2274,39 +2942,29 @@ internal virtual async Task InternalGetRunsAsync(string threadId, int? } /// - /// [Protocol Method] Gets a list of runs for a specified thread. + /// [Protocol Method] Returns a list of vector stores. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalGetRuns(string threadId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response GetVectorStores(int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRuns"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStores"); scope.Start(); try { - using HttpMessage message = CreateInternalGetRunsRequest(threadId, limit, order, after, before, context); + using HttpMessage message = CreateGetVectorStoresRequest(limit, order, after, before, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2316,40 +2974,36 @@ internal virtual Response InternalGetRuns(string threadId, int? limit, string or } } - /// Gets an existing run from an existing thread. - /// The ID of the thread to retrieve run information from. - /// The ID of the thread to retrieve information about. + /// Creates a vector store. + /// Request object for creating a vector store. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> GetRunAsync(string threadId, string runId, CancellationToken cancellationToken = default) + /// is null. + public virtual async Task> CreateVectorStoreAsync(VectorStoreOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(body, nameof(body)); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetRunAsync(threadId, runId, context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await CreateVectorStoreAsync(content, context).ConfigureAwait(false); + return Response.FromValue(VectorStore.FromResponse(response), response); } - /// Gets an existing run from an existing thread. - /// The ID of the thread to retrieve run information from. - /// The ID of the thread to retrieve information about. + /// Creates a vector store. + /// Request object for creating a vector store. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response GetRun(string threadId, string runId, CancellationToken cancellationToken = default) + /// is null. + public virtual Response CreateVectorStore(VectorStoreOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(body, nameof(body)); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetRun(threadId, runId, context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = CreateVectorStore(content, context); + return Response.FromValue(VectorStore.FromResponse(response), response); } /// - /// [Protocol Method] Gets an existing run from an existing thread. + /// [Protocol Method] Creates a vector store. /// /// /// @@ -2358,23 +3012,20 @@ public virtual Response GetRun(string threadId, string runId, Cancell /// /// /// - /// The ID of the thread to retrieve run information from. - /// The ID of the thread to retrieve information about. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetRunAsync(string threadId, string runId, RequestContext context) + internal virtual async Task CreateVectorStoreAsync(RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStore"); scope.Start(); try { - using HttpMessage message = CreateGetRunRequest(threadId, runId, context); + using HttpMessage message = CreateCreateVectorStoreRequest(content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2385,7 +3036,7 @@ internal virtual async Task GetRunAsync(string threadId, string runId, } /// - /// [Protocol Method] Gets an existing run from an existing thread. + /// [Protocol Method] Creates a vector store. /// /// /// @@ -2394,23 +3045,20 @@ internal virtual async Task GetRunAsync(string threadId, string runId, /// /// /// - /// The ID of the thread to retrieve run information from. - /// The ID of the thread to retrieve information about. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetRun(string threadId, string runId, RequestContext context) + internal virtual Response CreateVectorStore(RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStore"); scope.Start(); try { - using HttpMessage message = CreateGetRunRequest(threadId, runId, context); + using HttpMessage message = CreateCreateVectorStoreRequest(content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2420,44 +3068,36 @@ internal virtual Response GetRun(string threadId, string runId, RequestContext c } } - /// Modifies an existing thread run. - /// The ID of the thread associated with the specified run. - /// The ID of the run to modify. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Returns the vector store object matching the specified ID. + /// The ID of the vector store to retrieve. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> UpdateRunAsync(string threadId, string runId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetVectorStoreAsync(string vectorStoreId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - UpdateRunRequest updateRunRequest = new UpdateRunRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await UpdateRunAsync(threadId, runId, updateRunRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await GetVectorStoreAsync(vectorStoreId, context).ConfigureAwait(false); + return Response.FromValue(VectorStore.FromResponse(response), response); } - /// Modifies an existing thread run. - /// The ID of the thread associated with the specified run. - /// The ID of the run to modify. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Returns the vector store object matching the specified ID. + /// The ID of the vector store to retrieve. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response UpdateRun(string threadId, string runId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetVectorStore(string vectorStoreId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - UpdateRunRequest updateRunRequest = new UpdateRunRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = UpdateRun(threadId, runId, updateRunRequest.ToRequestContent(), context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = GetVectorStore(vectorStoreId, context); + return Response.FromValue(VectorStore.FromResponse(response), response); } /// - /// [Protocol Method] Modifies an existing thread run. + /// [Protocol Method] Returns the vector store object matching the specified ID. /// /// /// @@ -2466,25 +3106,21 @@ public virtual Response UpdateRun(string threadId, string runId, IRea /// /// /// - /// The ID of the thread associated with the specified run. - /// The ID of the run to modify. - /// The content to send as the body of the request. + /// The ID of the vector store to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task UpdateRunAsync(string threadId, string runId, RequestContent content, RequestContext context = null) + internal virtual async Task GetVectorStoreAsync(string vectorStoreId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStore"); scope.Start(); try { - using HttpMessage message = CreateUpdateRunRequest(threadId, runId, content, context); + using HttpMessage message = CreateGetVectorStoreRequest(vectorStoreId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2495,7 +3131,7 @@ internal virtual async Task UpdateRunAsync(string threadId, string run } /// - /// [Protocol Method] Modifies an existing thread run. + /// [Protocol Method] Returns the vector store object matching the specified ID. /// /// /// @@ -2503,26 +3139,22 @@ internal virtual async Task UpdateRunAsync(string threadId, string run /// /// /// - /// - /// The ID of the thread associated with the specified run. - /// The ID of the run to modify. - /// The content to send as the body of the request. + /// + /// The ID of the vector store to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response UpdateRun(string threadId, string runId, RequestContent content, RequestContext context = null) + internal virtual Response GetVectorStore(string vectorStoreId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStore"); scope.Start(); try { - using HttpMessage message = CreateUpdateRunRequest(threadId, runId, content, context); + using HttpMessage message = CreateGetVectorStoreRequest(vectorStoreId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2532,46 +3164,42 @@ internal virtual Response UpdateRun(string threadId, string runId, RequestConten } } - /// Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. - /// The ID of the thread that was run. - /// The ID of the run that requires tool outputs. - /// The list of tool outputs requested by tool calls from the specified run. + /// The ID of the vector store to modify. + /// The ID of the vector store to modify. + /// Request object for updating a vector store. /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> SubmitToolOutputsToRunAsync(string threadId, string runId, IEnumerable toolOutputs, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> ModifyVectorStoreAsync(string vectorStoreId, VectorStoreUpdateOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNull(toolOutputs, nameof(toolOutputs)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(body, nameof(body)); - SubmitToolOutputsToRunRequest submitToolOutputsToRunRequest = new SubmitToolOutputsToRunRequest(toolOutputs.ToList(), null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await SubmitToolOutputsToRunAsync(threadId, runId, submitToolOutputsToRunRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await ModifyVectorStoreAsync(vectorStoreId, content, context).ConfigureAwait(false); + return Response.FromValue(VectorStore.FromResponse(response), response); } - /// Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. - /// The ID of the thread that was run. - /// The ID of the run that requires tool outputs. - /// The list of tool outputs requested by tool calls from the specified run. + /// The ID of the vector store to modify. + /// The ID of the vector store to modify. + /// Request object for updating a vector store. /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response SubmitToolOutputsToRun(string threadId, string runId, IEnumerable toolOutputs, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response ModifyVectorStore(string vectorStoreId, VectorStoreUpdateOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNull(toolOutputs, nameof(toolOutputs)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(body, nameof(body)); - SubmitToolOutputsToRunRequest submitToolOutputsToRunRequest = new SubmitToolOutputsToRunRequest(toolOutputs.ToList(), null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = SubmitToolOutputsToRun(threadId, runId, submitToolOutputsToRunRequest.ToRequestContent(), context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = ModifyVectorStore(vectorStoreId, content, context); + return Response.FromValue(VectorStore.FromResponse(response), response); } /// - /// [Protocol Method] Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// [Protocol Method] The ID of the vector store to modify. /// /// /// @@ -2580,25 +3208,23 @@ public virtual Response SubmitToolOutputsToRun(string threadId, strin /// /// /// - /// The ID of the thread that was run. - /// The ID of the run that requires tool outputs. + /// The ID of the vector store to modify. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task SubmitToolOutputsToRunAsync(string threadId, string runId, RequestContent content, RequestContext context = null) + internal virtual async Task ModifyVectorStoreAsync(string vectorStoreId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.SubmitToolOutputsToRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.ModifyVectorStore"); scope.Start(); try { - using HttpMessage message = CreateSubmitToolOutputsToRunRequest(threadId, runId, content, context); + using HttpMessage message = CreateModifyVectorStoreRequest(vectorStoreId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2609,7 +3235,7 @@ internal virtual async Task SubmitToolOutputsToRunAsync(string threadI } /// - /// [Protocol Method] Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// [Protocol Method] The ID of the vector store to modify. /// /// /// @@ -2618,25 +3244,23 @@ internal virtual async Task SubmitToolOutputsToRunAsync(string threadI /// /// /// - /// The ID of the thread that was run. - /// The ID of the run that requires tool outputs. + /// The ID of the vector store to modify. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response SubmitToolOutputsToRun(string threadId, string runId, RequestContent content, RequestContext context = null) + internal virtual Response ModifyVectorStore(string vectorStoreId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.SubmitToolOutputsToRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.ModifyVectorStore"); scope.Start(); try { - using HttpMessage message = CreateSubmitToolOutputsToRunRequest(threadId, runId, content, context); + using HttpMessage message = CreateModifyVectorStoreRequest(vectorStoreId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2646,40 +3270,36 @@ internal virtual Response SubmitToolOutputsToRun(string threadId, string runId, } } - /// Cancels a run of an in progress thread. - /// The ID of the thread being run. - /// The ID of the run to cancel. + /// Deletes the vector store object matching the specified ID. + /// The ID of the vector store to delete. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> CancelRunAsync(string threadId, string runId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> DeleteVectorStoreAsync(string vectorStoreId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CancelRunAsync(threadId, runId, context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await DeleteVectorStoreAsync(vectorStoreId, context).ConfigureAwait(false); + return Response.FromValue(VectorStoreDeletionStatus.FromResponse(response), response); } - /// Cancels a run of an in progress thread. - /// The ID of the thread being run. - /// The ID of the run to cancel. + /// Deletes the vector store object matching the specified ID. + /// The ID of the vector store to delete. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response CancelRun(string threadId, string runId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response DeleteVectorStore(string vectorStoreId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = CancelRun(threadId, runId, context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = DeleteVectorStore(vectorStoreId, context); + return Response.FromValue(VectorStoreDeletionStatus.FromResponse(response), response); } /// - /// [Protocol Method] Cancels a run of an in progress thread. + /// [Protocol Method] Deletes the vector store object matching the specified ID. /// /// /// @@ -2688,23 +3308,21 @@ public virtual Response CancelRun(string threadId, string runId, Canc /// /// /// - /// The ID of the thread being run. - /// The ID of the run to cancel. + /// The ID of the vector store to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task CancelRunAsync(string threadId, string runId, RequestContext context) + internal virtual async Task DeleteVectorStoreAsync(string vectorStoreId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.DeleteVectorStore"); scope.Start(); try { - using HttpMessage message = CreateCancelRunRequest(threadId, runId, context); + using HttpMessage message = CreateDeleteVectorStoreRequest(vectorStoreId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2715,7 +3333,7 @@ internal virtual async Task CancelRunAsync(string threadId, string run } /// - /// [Protocol Method] Cancels a run of an in progress thread. + /// [Protocol Method] Deletes the vector store object matching the specified ID. /// /// /// @@ -2724,23 +3342,21 @@ internal virtual async Task CancelRunAsync(string threadId, string run /// /// /// - /// The ID of the thread being run. - /// The ID of the run to cancel. + /// The ID of the vector store to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response CancelRun(string threadId, string runId, RequestContext context) + internal virtual Response DeleteVectorStore(string vectorStoreId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.DeleteVectorStore"); scope.Start(); try { - using HttpMessage message = CreateCancelRunRequest(threadId, runId, context); + using HttpMessage message = CreateDeleteVectorStoreRequest(vectorStoreId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2750,36 +3366,46 @@ internal virtual Response CancelRun(string threadId, string runId, RequestContex } } - /// Creates a new assistant thread and immediately starts a run using that new thread. - /// Body parameter. + /// Returns a list of vector store files. + /// The ID of the vector store that the files belong to. + /// Filter by file status. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - public virtual async Task> CreateThreadAndRunAsync(CreateAndRunThreadOptions body, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetVectorStoreFilesAsync(string vectorStoreId, VectorStoreFileStatusFilter? filter = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNull(body, nameof(body)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateThreadAndRunAsync(content, context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await GetVectorStoreFilesAsync(vectorStoreId, filter?.ToString(), limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(OpenAIPageableListOfVectorStoreFile.FromResponse(response), response); } - /// Creates a new assistant thread and immediately starts a run using that new thread. - /// Body parameter. + /// Returns a list of vector store files. + /// The ID of the vector store that the files belong to. + /// Filter by file status. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - public virtual Response CreateThreadAndRun(CreateAndRunThreadOptions body, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetVectorStoreFiles(string vectorStoreId, VectorStoreFileStatusFilter? filter = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNull(body, nameof(body)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateThreadAndRun(content, context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = GetVectorStoreFiles(vectorStoreId, filter?.ToString(), limit, order?.ToString(), after, before, context); + return Response.FromValue(OpenAIPageableListOfVectorStoreFile.FromResponse(response), response); } /// - /// [Protocol Method] Creates a new assistant thread and immediately starts a run using that new thread. + /// [Protocol Method] Returns a list of vector store files. /// /// /// @@ -2788,20 +3414,26 @@ public virtual Response CreateThreadAndRun(CreateAndRunThreadOptions /// /// /// - /// The content to send as the body of the request. + /// The ID of the vector store that the files belong to. + /// Filter by file status. Allowed values: "in_progress" | "completed" | "failed" | "cancelled". + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task CreateThreadAndRunAsync(RequestContent content, RequestContext context = null) + internal virtual async Task GetVectorStoreFilesAsync(string vectorStoreId, string filter, int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThreadAndRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFiles"); scope.Start(); try { - using HttpMessage message = CreateCreateThreadAndRunRequest(content, context); + using HttpMessage message = CreateGetVectorStoreFilesRequest(vectorStoreId, filter, limit, order, after, before, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2812,7 +3444,7 @@ internal virtual async Task CreateThreadAndRunAsync(RequestContent con } /// - /// [Protocol Method] Creates a new assistant thread and immediately starts a run using that new thread. + /// [Protocol Method] Returns a list of vector store files. /// /// /// @@ -2821,20 +3453,26 @@ internal virtual async Task CreateThreadAndRunAsync(RequestContent con /// /// /// - /// The content to send as the body of the request. + /// The ID of the vector store that the files belong to. + /// Filter by file status. Allowed values: "in_progress" | "completed" | "failed" | "cancelled". + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response CreateThreadAndRun(RequestContent content, RequestContext context = null) + internal virtual Response GetVectorStoreFiles(string vectorStoreId, string filter, int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThreadAndRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFiles"); scope.Start(); try { - using HttpMessage message = CreateCreateThreadAndRunRequest(content, context); + using HttpMessage message = CreateGetVectorStoreFilesRequest(vectorStoreId, filter, limit, order, after, before, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2844,44 +3482,44 @@ internal virtual Response CreateThreadAndRun(RequestContent content, RequestCont } } - /// Gets a single run step from a thread run. - /// The ID of the thread that was run. - /// The ID of the specific run to retrieve the step from. - /// The ID of the step to retrieve information about. + /// Create a vector store file by attaching a file to a vector store. + /// The ID of the vector store for which to create a File. + /// A File ID that the vector store should use. Useful for tools like `file_search` that can access files. + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public virtual async Task> GetRunStepAsync(string threadId, string runId, string stepId, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CreateVectorStoreFileAsync(string vectorStoreId, string fileId, VectorStoreChunkingStrategyRequest chunkingStrategy = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(fileId, nameof(fileId)); + CreateVectorStoreFileRequest createVectorStoreFileRequest = new CreateVectorStoreFileRequest(fileId, chunkingStrategy, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetRunStepAsync(threadId, runId, stepId, context).ConfigureAwait(false); - return Response.FromValue(RunStep.FromResponse(response), response); + Response response = await CreateVectorStoreFileAsync(vectorStoreId, createVectorStoreFileRequest.ToRequestContent(), context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFile.FromResponse(response), response); } - /// Gets a single run step from a thread run. - /// The ID of the thread that was run. - /// The ID of the specific run to retrieve the step from. - /// The ID of the step to retrieve information about. + /// Create a vector store file by attaching a file to a vector store. + /// The ID of the vector store for which to create a File. + /// A File ID that the vector store should use. Useful for tools like `file_search` that can access files. + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public virtual Response GetRunStep(string threadId, string runId, string stepId, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CreateVectorStoreFile(string vectorStoreId, string fileId, VectorStoreChunkingStrategyRequest chunkingStrategy = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(fileId, nameof(fileId)); + CreateVectorStoreFileRequest createVectorStoreFileRequest = new CreateVectorStoreFileRequest(fileId, chunkingStrategy, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetRunStep(threadId, runId, stepId, context); - return Response.FromValue(RunStep.FromResponse(response), response); + Response response = CreateVectorStoreFile(vectorStoreId, createVectorStoreFileRequest.ToRequestContent(), context); + return Response.FromValue(VectorStoreFile.FromResponse(response), response); } /// - /// [Protocol Method] Gets a single run step from a thread run. + /// [Protocol Method] Create a vector store file by attaching a file to a vector store. /// /// /// @@ -2890,25 +3528,23 @@ public virtual Response GetRunStep(string threadId, string runId, strin /// /// /// - /// The ID of the thread that was run. - /// The ID of the specific run to retrieve the step from. - /// The ID of the step to retrieve information about. + /// The ID of the vector store for which to create a File. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetRunStepAsync(string threadId, string runId, string stepId, RequestContext context) + internal virtual async Task CreateVectorStoreFileAsync(string vectorStoreId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRunStep"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateGetRunStepRequest(threadId, runId, stepId, context); + using HttpMessage message = CreateCreateVectorStoreFileRequest(vectorStoreId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2919,7 +3555,7 @@ internal virtual async Task GetRunStepAsync(string threadId, string ru } /// - /// [Protocol Method] Gets a single run step from a thread run. + /// [Protocol Method] Create a vector store file by attaching a file to a vector store. /// /// /// @@ -2928,25 +3564,23 @@ internal virtual async Task GetRunStepAsync(string threadId, string ru /// /// /// - /// The ID of the thread that was run. - /// The ID of the specific run to retrieve the step from. - /// The ID of the step to retrieve information about. + /// The ID of the vector store for which to create a File. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetRunStep(string threadId, string runId, string stepId, RequestContext context) + internal virtual Response CreateVectorStoreFile(string vectorStoreId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRunStep"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateGetRunStepRequest(threadId, runId, stepId, context); + using HttpMessage message = CreateCreateVectorStoreFileRequest(vectorStoreId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2956,82 +3590,65 @@ internal virtual Response GetRunStep(string threadId, string runId, string stepI } } - /// Gets a list of run steps from a thread run. - /// The ID of the thread that was run. - /// The ID of the run to list steps from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Retrieves a vector store file. + /// The ID of the vector store that the file belongs to. + /// The ID of the file being retrieved. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalGetRunStepsAsync(string threadId, string runId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetVectorStoreFileAsync(string vectorStoreId, string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalGetRunStepsAsync(threadId, runId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); - return Response.FromValue(InternalOpenAIPageableListOfRunStep.FromResponse(response), response); + Response response = await GetVectorStoreFileAsync(vectorStoreId, fileId, context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFile.FromResponse(response), response); } - /// Gets a list of run steps from a thread run. - /// The ID of the thread that was run. - /// The ID of the run to list steps from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Retrieves a vector store file. + /// The ID of the vector store that the file belongs to. + /// The ID of the file being retrieved. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual Response InternalGetRunSteps(string threadId, string runId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetVectorStoreFile(string vectorStoreId, string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalGetRunSteps(threadId, runId, limit, order?.ToString(), after, before, context); - return Response.FromValue(InternalOpenAIPageableListOfRunStep.FromResponse(response), response); + Response response = GetVectorStoreFile(vectorStoreId, fileId, context); + return Response.FromValue(VectorStoreFile.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of run steps from a thread run. + /// [Protocol Method] Retrieves a vector store file. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread that was run. - /// The ID of the run to list steps from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the vector store that the file belongs to. + /// The ID of the file being retrieved. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalGetRunStepsAsync(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) + internal virtual async Task GetVectorStoreFileAsync(string vectorStoreId, string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRunSteps"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateInternalGetRunStepsRequest(threadId, runId, limit, order, after, before, context); + using HttpMessage message = CreateGetVectorStoreFileRequest(vectorStoreId, fileId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3042,41 +3659,32 @@ internal virtual async Task InternalGetRunStepsAsync(string threadId, } /// - /// [Protocol Method] Gets a list of run steps from a thread run. + /// [Protocol Method] Retrieves a vector store file. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread that was run. - /// The ID of the run to list steps from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the vector store that the file belongs to. + /// The ID of the file being retrieved. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalGetRunSteps(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response GetVectorStoreFile(string vectorStoreId, string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRunSteps"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateInternalGetRunStepsRequest(threadId, runId, limit, order, after, before, context); + using HttpMessage message = CreateGetVectorStoreFileRequest(vectorStoreId, fileId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3086,52 +3694,72 @@ internal virtual Response InternalGetRunSteps(string threadId, string runId, int } } - /// Gets a list of previously uploaded files. - /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// + /// Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. + /// To delete the file, use the delete file endpoint. + /// + /// The ID of the vector store that the file belongs to. + /// The ID of the file to delete its relationship to the vector store. /// The cancellation token to use. - internal virtual async Task> InternalListFilesAsync(OpenAIFilePurpose? purpose = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> DeleteVectorStoreFileAsync(string vectorStoreId, string fileId, CancellationToken cancellationToken = default) { + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalListFilesAsync(purpose?.ToString(), context).ConfigureAwait(false); - return Response.FromValue(InternalFileListResponse.FromResponse(response), response); + Response response = await DeleteVectorStoreFileAsync(vectorStoreId, fileId, context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFileDeletionStatus.FromResponse(response), response); } - /// Gets a list of previously uploaded files. - /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// + /// Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. + /// To delete the file, use the delete file endpoint. + /// + /// The ID of the vector store that the file belongs to. + /// The ID of the file to delete its relationship to the vector store. /// The cancellation token to use. - internal virtual Response InternalListFiles(OpenAIFilePurpose? purpose = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response DeleteVectorStoreFile(string vectorStoreId, string fileId, CancellationToken cancellationToken = default) { + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalListFiles(purpose?.ToString(), context); - return Response.FromValue(InternalFileListResponse.FromResponse(response), response); + Response response = DeleteVectorStoreFile(vectorStoreId, fileId, context); + return Response.FromValue(VectorStoreFileDeletionStatus.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of previously uploaded files. + /// [Protocol Method] Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. + /// To delete the file, use the delete file endpoint. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output". + /// The ID of the vector store that the file belongs to. + /// The ID of the file to delete its relationship to the vector store. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalListFilesAsync(string purpose, RequestContext context) + internal virtual async Task DeleteVectorStoreFileAsync(string vectorStoreId, string fileId, RequestContext context) { - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalListFiles"); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.DeleteVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateInternalListFilesRequest(purpose, context); + using HttpMessage message = CreateDeleteVectorStoreFileRequest(vectorStoreId, fileId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3142,31 +3770,33 @@ internal virtual async Task InternalListFilesAsync(string purpose, Req } /// - /// [Protocol Method] Gets a list of previously uploaded files. + /// [Protocol Method] Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. + /// To delete the file, use the delete file endpoint. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output". + /// The ID of the vector store that the file belongs to. + /// The ID of the file to delete its relationship to the vector store. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalListFiles(string purpose, RequestContext context) + internal virtual Response DeleteVectorStoreFile(string vectorStoreId, string fileId, RequestContext context) { - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalListFiles"); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.DeleteVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateInternalListFilesRequest(purpose, context); + using HttpMessage message = CreateDeleteVectorStoreFileRequest(vectorStoreId, fileId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3176,42 +3806,44 @@ internal virtual Response InternalListFiles(string purpose, RequestContext conte } } - /// Uploads a file for use by other operations. - /// The file data (not filename) to upload. - /// The intended purpose of the file. - /// A filename to associate with the uploaded data. + /// Create a vector store file batch. + /// The ID of the vector store for which to create a File Batch. + /// A list of File IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. /// The cancellation token to use. - /// is null. - public virtual async Task> UploadFileAsync(Stream data, OpenAIFilePurpose purpose, string filename = null, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CreateVectorStoreFileBatchAsync(string vectorStoreId, IEnumerable fileIds, VectorStoreChunkingStrategyRequest chunkingStrategy = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNull(data, nameof(data)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(fileIds, nameof(fileIds)); - UploadFileRequest uploadFileRequest = new UploadFileRequest(data, purpose, filename, null); - using MultipartFormDataRequestContent content = uploadFileRequest.ToMultipartRequestContent(); + CreateVectorStoreFileBatchRequest createVectorStoreFileBatchRequest = new CreateVectorStoreFileBatchRequest(fileIds.ToList(), chunkingStrategy, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await UploadFileAsync(content, content.ContentType, context).ConfigureAwait(false); - return Response.FromValue(OpenAIFile.FromResponse(response), response); + Response response = await CreateVectorStoreFileBatchAsync(vectorStoreId, createVectorStoreFileBatchRequest.ToRequestContent(), context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } - /// Uploads a file for use by other operations. - /// The file data (not filename) to upload. - /// The intended purpose of the file. - /// A filename to associate with the uploaded data. + /// Create a vector store file batch. + /// The ID of the vector store for which to create a File Batch. + /// A list of File IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. /// The cancellation token to use. - /// is null. - public virtual Response UploadFile(Stream data, OpenAIFilePurpose purpose, string filename = null, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CreateVectorStoreFileBatch(string vectorStoreId, IEnumerable fileIds, VectorStoreChunkingStrategyRequest chunkingStrategy = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNull(data, nameof(data)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(fileIds, nameof(fileIds)); - UploadFileRequest uploadFileRequest = new UploadFileRequest(data, purpose, filename, null); - using MultipartFormDataRequestContent content = uploadFileRequest.ToMultipartRequestContent(); + CreateVectorStoreFileBatchRequest createVectorStoreFileBatchRequest = new CreateVectorStoreFileBatchRequest(fileIds.ToList(), chunkingStrategy, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = UploadFile(content, content.ContentType, context); - return Response.FromValue(OpenAIFile.FromResponse(response), response); + Response response = CreateVectorStoreFileBatch(vectorStoreId, createVectorStoreFileBatchRequest.ToRequestContent(), context); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } /// - /// [Protocol Method] Uploads a file for use by other operations. + /// [Protocol Method] Create a vector store file batch. /// /// /// @@ -3220,21 +3852,23 @@ public virtual Response UploadFile(Stream data, OpenAIFilePurpose pu /// /// /// + /// The ID of the vector store for which to create a File Batch. /// The content to send as the body of the request. - /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task UploadFileAsync(RequestContent content, string contentType, RequestContext context = null) + internal virtual async Task CreateVectorStoreFileBatchAsync(string vectorStoreId, RequestContent content, RequestContext context = null) { + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UploadFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + using HttpMessage message = CreateCreateVectorStoreFileBatchRequest(vectorStoreId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3245,7 +3879,7 @@ internal virtual async Task UploadFileAsync(RequestContent content, st } /// - /// [Protocol Method] Uploads a file for use by other operations. + /// [Protocol Method] Create a vector store file batch. /// /// /// @@ -3254,21 +3888,23 @@ internal virtual async Task UploadFileAsync(RequestContent content, st /// /// /// + /// The ID of the vector store for which to create a File Batch. /// The content to send as the body of the request. - /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response UploadFile(RequestContent content, string contentType, RequestContext context = null) + internal virtual Response CreateVectorStoreFileBatch(string vectorStoreId, RequestContent content, RequestContext context = null) { + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UploadFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + using HttpMessage message = CreateCreateVectorStoreFileBatchRequest(vectorStoreId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3278,64 +3914,65 @@ internal virtual Response UploadFile(RequestContent content, string contentType, } } - /// Delete a previously uploaded file. - /// The ID of the file to delete. + /// Retrieve a vector store file batch. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch being retrieved. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalDeleteFileAsync(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetVectorStoreFileBatchAsync(string vectorStoreId, string batchId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalDeleteFileAsync(fileId, context).ConfigureAwait(false); - return Response.FromValue(InternalFileDeletionStatus.FromResponse(response), response); + Response response = await GetVectorStoreFileBatchAsync(vectorStoreId, batchId, context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } - /// Delete a previously uploaded file. - /// The ID of the file to delete. + /// Retrieve a vector store file batch. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch being retrieved. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual Response InternalDeleteFile(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetVectorStoreFileBatch(string vectorStoreId, string batchId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalDeleteFile(fileId, context); - return Response.FromValue(InternalFileDeletionStatus.FromResponse(response), response); + Response response = GetVectorStoreFileBatch(vectorStoreId, batchId, context); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } /// - /// [Protocol Method] Delete a previously uploaded file. + /// [Protocol Method] Retrieve a vector store file batch. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the file to delete. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch being retrieved. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalDeleteFileAsync(string fileId, RequestContext context) + internal virtual async Task GetVectorStoreFileBatchAsync(string vectorStoreId, string batchId, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateInternalDeleteFileRequest(fileId, context); + using HttpMessage message = CreateGetVectorStoreFileBatchRequest(vectorStoreId, batchId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3346,35 +3983,32 @@ internal virtual async Task InternalDeleteFileAsync(string fileId, Req } /// - /// [Protocol Method] Delete a previously uploaded file. + /// [Protocol Method] Retrieve a vector store file batch. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the file to delete. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch being retrieved. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalDeleteFile(string fileId, RequestContext context) + internal virtual Response GetVectorStoreFileBatch(string vectorStoreId, string batchId, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateInternalDeleteFileRequest(fileId, context); + using HttpMessage message = CreateGetVectorStoreFileBatchRequest(vectorStoreId, batchId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3384,36 +4018,40 @@ internal virtual Response InternalDeleteFile(string fileId, RequestContext conte } } - /// Returns information about a specific file. Does not retrieve file content. - /// The ID of the file to retrieve. + /// Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch to cancel. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual async Task> GetFileAsync(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> CancelVectorStoreFileBatchAsync(string vectorStoreId, string batchId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetFileAsync(fileId, context).ConfigureAwait(false); - return Response.FromValue(OpenAIFile.FromResponse(response), response); + Response response = await CancelVectorStoreFileBatchAsync(vectorStoreId, batchId, context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } - /// Returns information about a specific file. Does not retrieve file content. - /// The ID of the file to retrieve. + /// Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch to cancel. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual Response GetFile(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response CancelVectorStoreFileBatch(string vectorStoreId, string batchId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetFile(fileId, context); - return Response.FromValue(OpenAIFile.FromResponse(response), response); + Response response = CancelVectorStoreFileBatch(vectorStoreId, batchId, context); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } /// - /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// [Protocol Method] Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. /// /// /// @@ -3422,21 +4060,23 @@ public virtual Response GetFile(string fileId, CancellationToken can /// /// /// - /// The ID of the file to retrieve. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch to cancel. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetFileAsync(string fileId, RequestContext context) + internal virtual async Task CancelVectorStoreFileBatchAsync(string vectorStoreId, string batchId, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateGetFileRequest(fileId, context); + using HttpMessage message = CreateCancelVectorStoreFileBatchRequest(vectorStoreId, batchId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3447,7 +4087,7 @@ internal virtual async Task GetFileAsync(string fileId, RequestContext } /// - /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// [Protocol Method] Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. /// /// /// @@ -3456,21 +4096,23 @@ internal virtual async Task GetFileAsync(string fileId, RequestContext /// /// /// - /// The ID of the file to retrieve. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch to cancel. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetFile(string fileId, RequestContext context) + internal virtual Response CancelVectorStoreFileBatch(string vectorStoreId, string batchId, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateGetFileRequest(fileId, context); + using HttpMessage message = CreateCancelVectorStoreFileBatchRequest(vectorStoreId, batchId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3480,36 +4122,50 @@ internal virtual Response GetFile(string fileId, RequestContext context) } } - /// Returns information about a specific file. Does not retrieve file content. - /// The ID of the file to retrieve. + /// Returns a list of vector store files in a batch. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch that the files belong to. + /// Filter by file status. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual async Task> GetFileContentAsync(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetVectorStoreFileBatchFilesAsync(string vectorStoreId, string batchId, VectorStoreFileStatusFilter? filter = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetFileContentAsync(fileId, context).ConfigureAwait(false); - return Response.FromValue(response.Content, response); + Response response = await GetVectorStoreFileBatchFilesAsync(vectorStoreId, batchId, filter?.ToString(), limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(OpenAIPageableListOfVectorStoreFile.FromResponse(response), response); } - /// Returns information about a specific file. Does not retrieve file content. - /// The ID of the file to retrieve. + /// Returns a list of vector store files in a batch. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch that the files belong to. + /// Filter by file status. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual Response GetFileContent(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetVectorStoreFileBatchFiles(string vectorStoreId, string batchId, VectorStoreFileStatusFilter? filter = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetFileContent(fileId, context); - return Response.FromValue(response.Content, response); + Response response = GetVectorStoreFileBatchFiles(vectorStoreId, batchId, filter?.ToString(), limit, order?.ToString(), after, before, context); + return Response.FromValue(OpenAIPageableListOfVectorStoreFile.FromResponse(response), response); } /// - /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// [Protocol Method] Returns a list of vector store files in a batch. /// /// /// @@ -3518,21 +4174,28 @@ public virtual Response GetFileContent(string fileId, CancellationTo /// /// /// - /// The ID of the file to retrieve. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch that the files belong to. + /// Filter by file status. Allowed values: "in_progress" | "completed" | "failed" | "cancelled". + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetFileContentAsync(string fileId, RequestContext context) + internal virtual async Task GetVectorStoreFileBatchFilesAsync(string vectorStoreId, string batchId, string filter, int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFileContent"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFileBatchFiles"); scope.Start(); try { - using HttpMessage message = CreateGetFileContentRequest(fileId, context); + using HttpMessage message = CreateGetVectorStoreFileBatchFilesRequest(vectorStoreId, batchId, filter, limit, order, after, before, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3543,7 +4206,7 @@ internal virtual async Task GetFileContentAsync(string fileId, Request } /// - /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// [Protocol Method] Returns a list of vector store files in a batch. /// /// /// @@ -3552,21 +4215,28 @@ internal virtual async Task GetFileContentAsync(string fileId, Request /// /// /// - /// The ID of the file to retrieve. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch that the files belong to. + /// Filter by file status. Allowed values: "in_progress" | "completed" | "failed" | "cancelled". + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetFileContent(string fileId, RequestContext context) + internal virtual Response GetVectorStoreFileBatchFiles(string vectorStoreId, string batchId, string filter, int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFileContent"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFileBatchFiles"); scope.Start(); try { - using HttpMessage message = CreateGetFileContentRequest(fileId, context); + using HttpMessage message = CreateGetVectorStoreFileBatchFilesRequest(vectorStoreId, batchId, filter, limit, order, after, before, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3576,6 +4246,300 @@ internal virtual Response GetFileContent(string fileId, RequestContext context) } } + internal HttpMessage CreateInternalGetMessagesRequest(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/messages", false); + if (runId != null) + { + uri.AppendQuery("runId", runId, true); + } + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetVectorStoresRequest(int? limit, string order, string after, string before, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores", false); + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateVectorStoreRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetVectorStoreRequest(string vectorStoreId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateModifyVectorStoreRequest(string vectorStoreId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateDeleteVectorStoreRequest(string vectorStoreId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetVectorStoreFilesRequest(string vectorStoreId, string filter, int? limit, string order, string after, string before, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/files", false); + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateVectorStoreFileRequest(string vectorStoreId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/files", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetVectorStoreFileRequest(string vectorStoreId, string fileId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteVectorStoreFileRequest(string vectorStoreId, string fileId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateVectorStoreFileBatchRequest(string vectorStoreId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/file_batches", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetVectorStoreFileBatchRequest(string vectorStoreId, string batchId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/file_batches/", false); + uri.AppendPath(batchId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCancelVectorStoreFileBatchRequest(string vectorStoreId, string batchId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/file_batches/", false); + uri.AppendPath(batchId, true); + uri.AppendPath("/cancel", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetVectorStoreFileBatchFilesRequest(string vectorStoreId, string batchId, string filter, int? limit, string order, string after, string before, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/file_batches/", false); + uri.AppendPath(batchId, true); + uri.AppendPath("/files", false); + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + private static RequestContext DefaultRequestContext = new RequestContext(); internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) { diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClientOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClientOptions.cs index a847db2052bd..3436987e4b16 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClientOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClientOptions.cs @@ -13,13 +13,19 @@ namespace Azure.AI.OpenAI.Assistants /// Client options for AssistantsClient. public partial class AssistantsClientOptions : ClientOptions { - private const ServiceVersion LatestVersion = ServiceVersion.V2024_02_15_Preview; + private const ServiceVersion LatestVersion = ServiceVersion.V2024_09_01_Preview; /// The version of the service to use. public enum ServiceVersion { /// Service version "2024-02-15-preview". V2024_02_15_Preview = 1, + /// Service version "2024-05-01-preview". + V2024_05_01_Preview = 2, + /// Service version "2024-07-01-preview". + V2024_07_01_Preview = 3, + /// Service version "2024-09-01-preview". + V2024_09_01_Preview = 4, } internal string Version { get; } @@ -30,6 +36,9 @@ public AssistantsClientOptions(ServiceVersion version = LatestVersion) Version = version switch { ServiceVersion.V2024_02_15_Preview => "2024-02-15-preview", + ServiceVersion.V2024_05_01_Preview => "2024-05-01-preview", + ServiceVersion.V2024_07_01_Preview => "2024-07-01-preview", + ServiceVersion.V2024_09_01_Preview => "2024-09-01-preview", _ => throw new NotSupportedException() }; } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsModelFactory.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsModelFactory.cs index 8b4620e1331e..df72598f8277 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsModelFactory.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsModelFactory.cs @@ -5,6 +5,7 @@ #nullable disable +using System; using System.Collections.Generic; using System.Linq; @@ -21,15 +22,28 @@ public static partial class AssistantsModelFactory /// /// The collection of tools to enable for the new assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// - /// A list of previously uploaded file IDs to attach to the assistant. + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// The response format of the tool calls used by this assistant. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// A new instance for mocking. - public static AssistantCreationOptions AssistantCreationOptions(string model = null, string name = null, string description = null, string instructions = null, IEnumerable tools = null, IEnumerable fileIds = null, IDictionary metadata = null) + public static AssistantCreationOptions AssistantCreationOptions(string model = null, string name = null, string description = null, string instructions = null, IEnumerable tools = null, CreateToolResourcesOptions toolResources = null, float? temperature = null, float? topP = null, BinaryData responseFormat = null, IDictionary metadata = null) { tools ??= new List(); - fileIds ??= new List(); metadata ??= new Dictionary(); return new AssistantCreationOptions( @@ -38,37 +52,94 @@ public static AssistantCreationOptions AssistantCreationOptions(string model = n description, instructions, tools?.ToList(), - fileIds?.ToList(), + toolResources, + temperature, + topP, + responseFormat, metadata, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The role associated with the assistant thread message. Currently, only 'user' is supported when providing initial messages to a new thread. - /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via a separate call to the create message API. - /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. + /// Initializes a new instance of . + /// A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . /// /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - /// A new instance for mocking. - public static ThreadInitializationMessage ThreadInitializationMessage(MessageRole role = default, string content = null, IEnumerable fileIds = null, IDictionary metadata = null) + /// A new instance for mocking. + public static CreateFileSearchToolResourceVectorStoreOptions CreateFileSearchToolResourceVectorStoreOptions(IEnumerable fileIds = null, VectorStoreChunkingStrategyRequest chunkingStrategy = null, IDictionary metadata = null) { fileIds ??= new List(); metadata ??= new Dictionary(); - return new ThreadInitializationMessage(role, content, fileIds?.ToList(), metadata, serializedAdditionalRawData: null); + return new CreateFileSearchToolResourceVectorStoreOptions(fileIds?.ToList(), chunkingStrategy, metadata, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The object type. - /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. - /// A new instance for mocking. - public static MessageTextAnnotation MessageTextAnnotation(string type = null, string text = null, int startIndex = default, int endIndex = default) + /// Initializes a new instance of . + /// The options for the static chunking strategy. + /// A new instance for mocking. + public static VectorStoreStaticChunkingStrategyRequest VectorStoreStaticChunkingStrategyRequest(VectorStoreStaticChunkingStrategyOptions @static = null) + { + return new VectorStoreStaticChunkingStrategyRequest(VectorStoreChunkingStrategyRequestType.Static, serializedAdditionalRawData: null, @static); + } + + /// Initializes a new instance of . + /// Resources to be used by the `code_interpreter tool` consisting of file IDs. + /// Resources to be used by the `file_search` tool consisting of vector store IDs. + /// A new instance for mocking. + public static ToolResources ToolResources(CodeInterpreterToolResource codeInterpreter = null, FileSearchToolResource fileSearch = null) + { + return new ToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + /// A new instance for mocking. + public static CodeInterpreterToolResource CodeInterpreterToolResource(IEnumerable fileIds = null) + { + fileIds ??= new List(); + + return new CodeInterpreterToolResource(fileIds?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The ID of the vector store attached to this assistant. There can be a maximum of 1 vector + /// store attached to the assistant. + /// + /// A new instance for mocking. + public static FileSearchToolResource FileSearchToolResource(IEnumerable vectorStoreIds = null) + { + vectorStoreIds ??= new List(); + + return new FileSearchToolResource(vectorStoreIds?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The role of the entity that is creating the message. Allowed values include: + /// - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + /// - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into + /// the conversation. + /// + /// + /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via + /// a separate call to the create message API. + /// + /// A list of files attached to the message, and the tools they should be added to. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// A new instance for mocking. + public static ThreadMessageOptions ThreadMessageOptions(MessageRole role = default, string content = null, IEnumerable attachments = null, IDictionary metadata = null) { - return new UnknownMessageTextAnnotation(type, text, startIndex, endIndex, serializedAdditionalRawData: null); + attachments ??= new List(); + metadata ??= new Dictionary(); + + return new ThreadMessageOptions(role, content, attachments?.ToList(), metadata, serializedAdditionalRawData: null); } /// Initializes a new instance of . @@ -79,15 +150,46 @@ public static MessageTextAnnotation MessageTextAnnotation(string type = null, st /// Additional instructions to append at the end of the instructions for the run. This is useful for modifying the behavior /// on a per-run basis without overriding other instructions. /// + /// Adds additional messages to the thread before creating the run. /// /// The overridden list of enabled tools that the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// + /// Whether to enable parallel function calling during tool use. + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort + /// to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of + /// completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Specifies the format that the model must output. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// A new instance for mocking. - public static CreateRunOptions CreateRunOptions(string assistantId = null, string overrideModelName = null, string overrideInstructions = null, string additionalInstructions = null, IEnumerable overrideTools = null, IDictionary metadata = null) + public static CreateRunOptions CreateRunOptions(string assistantId = null, string overrideModelName = null, string overrideInstructions = null, string additionalInstructions = null, IEnumerable additionalMessages = null, IEnumerable overrideTools = null, bool? parallelToolCalls = null, bool? stream = null, float? temperature = null, float? topP = null, int? maxPromptTokens = null, int? maxCompletionTokens = null, TruncationObject truncationStrategy = null, BinaryData toolChoice = null, BinaryData responseFormat = null, IDictionary metadata = null) { + additionalMessages ??= new List(); overrideTools ??= new List(); metadata ??= new Dictionary(); @@ -96,7 +198,17 @@ public static CreateRunOptions CreateRunOptions(string assistantId = null, strin overrideModelName, overrideInstructions, additionalInstructions, + additionalMessages?.ToList(), overrideTools?.ToList(), + parallelToolCalls, + stream, + temperature, + topP, + maxPromptTokens, + maxCompletionTokens, + truncationStrategy, + toolChoice, + responseFormat, metadata, serializedAdditionalRawData: null); } @@ -119,19 +231,59 @@ public static RunError RunError(string code = null, string message = null) return new RunError(code, message, serializedAdditionalRawData: null); } + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run. + /// Number of prompt tokens used over the course of the run. + /// Total number of tokens used (prompt + completion). + /// A new instance for mocking. + public static RunCompletionUsage RunCompletionUsage(long completionTokens = default, long promptTokens = default, long totalTokens = default) + { + return new RunCompletionUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData: null); + } + /// Initializes a new instance of . /// The ID of the assistant for which the thread should be created. - /// The details used to create the new thread. + /// The details used to create the new thread. If no thread is provided, an empty one will be created. /// The overridden model that the assistant should use to run the thread. /// The overridden system instructions the assistant should use to run the thread. /// /// The overridden list of enabled tools the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . + /// + /// Whether to enable parallel function calling during tool use. + /// Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. /// + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens + /// specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Specifies the format that the model must output. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// A new instance for mocking. - public static CreateAndRunThreadOptions CreateAndRunThreadOptions(string assistantId = null, AssistantThreadCreationOptions thread = null, string overrideModelName = null, string overrideInstructions = null, IEnumerable overrideTools = null, IDictionary metadata = null) + public static CreateAndRunThreadOptions CreateAndRunThreadOptions(string assistantId = null, AssistantThreadCreationOptions thread = null, string overrideModelName = null, string overrideInstructions = null, IEnumerable overrideTools = null, bool? parallelToolCalls = null, UpdateToolResourcesOptions toolResources = null, bool? stream = null, float? temperature = null, float? topP = null, int? maxPromptTokens = null, int? maxCompletionTokens = null, TruncationObject truncationStrategy = null, BinaryData toolChoice = null, BinaryData responseFormat = null, IDictionary metadata = null) { overrideTools ??= new List(); metadata ??= new Dictionary(); @@ -142,6 +294,16 @@ public static CreateAndRunThreadOptions CreateAndRunThreadOptions(string assista overrideModelName, overrideInstructions, overrideTools?.ToList(), + parallelToolCalls, + toolResources, + stream, + temperature, + topP, + maxPromptTokens, + maxCompletionTokens, + truncationStrategy, + toolChoice, + responseFormat, metadata, serializedAdditionalRawData: null); } @@ -166,7 +328,7 @@ public static RunStepMessageCreationReference RunStepMessageCreationReference(st /// /// A list of tool call details for this run step. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// /// A new instance for mocking. public static RunStepToolCallDetails RunStepToolCallDetails(IEnumerable toolCalls = null) @@ -209,15 +371,15 @@ public static RunStepCodeInterpreterImageReference RunStepCodeInterpreterImageRe return new RunStepCodeInterpreterImageReference(fileId, serializedAdditionalRawData: null); } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The ID of the tool call. This ID must be referenced when you submit tool outputs. - /// The key/value pairs produced by the retrieval tool. - /// A new instance for mocking. - public static RunStepRetrievalToolCall RunStepRetrievalToolCall(string id = null, IReadOnlyDictionary retrieval = null) + /// Reserved for future use. + /// A new instance for mocking. + public static RunStepFileSearchToolCall RunStepFileSearchToolCall(string id = null, IReadOnlyDictionary fileSearch = null) { - retrieval ??= new Dictionary(); + fileSearch ??= new Dictionary(); - return new RunStepRetrievalToolCall("retrieval", id, serializedAdditionalRawData: null, retrieval); + return new RunStepFileSearchToolCall("file_search", id, serializedAdditionalRawData: null, fileSearch); } /// Initializes a new instance of . @@ -228,5 +390,488 @@ public static RunStepError RunStepError(RunStepErrorCode code = default, string { return new RunStepError(code, message, serializedAdditionalRawData: null); } + + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run step. + /// Number of prompt tokens used over the course of the run step. + /// Total number of tokens used (prompt + completion). + /// A new instance for mocking. + public static RunStepCompletionUsage RunStepCompletionUsage(long completionTokens = default, long promptTokens = default, long totalTokens = default) + { + return new RunStepCompletionUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The object type, which is always list. + /// The requested list of items. + /// The first ID represented in this list. + /// The last ID represented in this list. + /// A value indicating whether there are additional values available not captured in this list. + /// A new instance for mocking. + public static OpenAIPageableListOfVectorStore OpenAIPageableListOfVectorStore(OpenAIPageableListOfVectorStoreObject @object = default, IEnumerable data = null, string firstId = null, string lastId = null, bool hasMore = default) + { + data ??= new List(); + + return new OpenAIPageableListOfVectorStore( + @object, + data?.ToList(), + firstId, + lastId, + hasMore, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store`. + /// The Unix timestamp (in seconds) for when the vector store was created. + /// The name of the vector store. + /// The total number of bytes used by the files in the vector store. + /// Files count grouped by status processed or being processed by this vector store. + /// The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + /// Details on when this vector store expires. + /// The Unix timestamp (in seconds) for when the vector store will expire. + /// The Unix timestamp (in seconds) for when the vector store was last active. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// A new instance for mocking. + public static VectorStore VectorStore(string id = null, VectorStoreObject @object = default, DateTimeOffset createdAt = default, string name = null, int usageBytes = default, VectorStoreFileCount fileCounts = null, VectorStoreStatus status = default, VectorStoreExpirationPolicy expiresAfter = null, DateTimeOffset? expiresAt = null, DateTimeOffset? lastActiveAt = null, IReadOnlyDictionary metadata = null) + { + metadata ??= new Dictionary(); + + return new VectorStore( + id, + @object, + createdAt, + name, + usageBytes, + fileCounts, + status, + expiresAfter, + expiresAt, + lastActiveAt, + metadata, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The number of files that are currently being processed. + /// The number of files that have been successfully processed. + /// The number of files that have failed to process. + /// The number of files that were cancelled. + /// The total number of files. + /// A new instance for mocking. + public static VectorStoreFileCount VectorStoreFileCount(int inProgress = default, int completed = default, int failed = default, int cancelled = default, int total = default) + { + return new VectorStoreFileCount( + inProgress, + completed, + failed, + cancelled, + total, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// The object type, which is always 'vector_store.deleted'. + /// A new instance for mocking. + public static VectorStoreDeletionStatus VectorStoreDeletionStatus(string id = null, bool deleted = default, VectorStoreDeletionStatusObject @object = default) + { + return new VectorStoreDeletionStatus(id, deleted, @object, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The object type, which is always list. + /// The requested list of items. + /// The first ID represented in this list. + /// The last ID represented in this list. + /// A value indicating whether there are additional values available not captured in this list. + /// A new instance for mocking. + public static OpenAIPageableListOfVectorStoreFile OpenAIPageableListOfVectorStoreFile(OpenAIPageableListOfVectorStoreFileObject @object = default, IEnumerable data = null, string firstId = null, string lastId = null, bool hasMore = default) + { + data ??= new List(); + + return new OpenAIPageableListOfVectorStoreFile( + @object, + data?.ToList(), + firstId, + lastId, + hasMore, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store.file`. + /// + /// The total vector store usage in bytes. Note that this may be different from the original file + /// size. + /// + /// The Unix timestamp (in seconds) for when the vector store file was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + /// The last error associated with this vector store file. Will be `null` if there are no errors. + /// + /// The strategy used to chunk the file. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static VectorStoreFile VectorStoreFile(string id = null, VectorStoreFileObject @object = default, int usageBytes = default, DateTimeOffset createdAt = default, string vectorStoreId = null, VectorStoreFileStatus status = default, VectorStoreFileError lastError = null, VectorStoreChunkingStrategyResponse chunkingStrategy = null) + { + return new VectorStoreFile( + id, + @object, + usageBytes, + createdAt, + vectorStoreId, + status, + lastError, + chunkingStrategy, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// One of `server_error` or `rate_limit_exceeded`. + /// A human-readable description of the error. + /// A new instance for mocking. + public static VectorStoreFileError VectorStoreFileError(VectorStoreFileErrorCode code = default, string message = null) + { + return new VectorStoreFileError(code, message, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The options for the static chunking strategy. + /// A new instance for mocking. + public static VectorStoreStaticChunkingStrategyResponse VectorStoreStaticChunkingStrategyResponse(VectorStoreStaticChunkingStrategyOptions @static = null) + { + return new VectorStoreStaticChunkingStrategyResponse(VectorStoreChunkingStrategyResponseType.Static, serializedAdditionalRawData: null, @static); + } + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// The object type, which is always 'vector_store.deleted'. + /// A new instance for mocking. + public static VectorStoreFileDeletionStatus VectorStoreFileDeletionStatus(string id = null, bool deleted = default, VectorStoreFileDeletionStatusObject @object = default) + { + return new VectorStoreFileDeletionStatus(id, deleted, @object, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store.file_batch`. + /// The Unix timestamp (in seconds) for when the vector store files batch was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + /// Files count grouped by status processed or being processed by this vector store. + /// A new instance for mocking. + public static VectorStoreFileBatch VectorStoreFileBatch(string id = null, VectorStoreFileBatchObject @object = default, DateTimeOffset createdAt = default, string vectorStoreId = null, VectorStoreFileBatchStatus status = default, VectorStoreFileCount fileCounts = null) + { + return new VectorStoreFileBatch( + id, + @object, + createdAt, + vectorStoreId, + status, + fileCounts, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier of the message, which can be referenced in API endpoints. + /// The object type, which is always `thread.message.delta`. + /// The delta containing the fields that have changed on the Message. + /// A new instance for mocking. + public static MessageDeltaChunk MessageDeltaChunk(string id = null, MessageDeltaChunkObject @object = default, MessageDelta delta = null) + { + return new MessageDeltaChunk(id, @object, delta, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The entity that produced the message. + /// + /// The content of the message as an array of text and/or images. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static MessageDelta MessageDelta(MessageRole role = default, IEnumerable content = null) + { + content ??= new List(); + + return new MessageDelta(role, content?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The type of content for this content part. + /// A new instance for mocking. + public static MessageDeltaContent MessageDeltaContent(int index = default, string type = null) + { + return new UnknownMessageDeltaContent(index, type, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The image_file data. + /// A new instance for mocking. + public static MessageDeltaImageFileContent MessageDeltaImageFileContent(int index = default, MessageDeltaImageFileContentObject imageFile = null) + { + return new MessageDeltaImageFileContent(index, "image_file", serializedAdditionalRawData: null, imageFile); + } + + /// Initializes a new instance of . + /// The file ID of the image in the message content. + /// A new instance for mocking. + public static MessageDeltaImageFileContentObject MessageDeltaImageFileContentObject(string fileId = null) + { + return new MessageDeltaImageFileContentObject(fileId, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The text content details. + /// A new instance for mocking. + public static MessageDeltaTextContentObject MessageDeltaTextContentObject(int index = default, MessageDeltaTextContent text = null) + { + return new MessageDeltaTextContentObject(index, "text", serializedAdditionalRawData: null, text); + } + + /// Initializes a new instance of . + /// The data that makes up the text. + /// + /// Annotations for the text. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static MessageDeltaTextContent MessageDeltaTextContent(string value = null, IEnumerable annotations = null) + { + annotations ??= new List(); + + return new MessageDeltaTextContent(value, annotations?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The type of the text content annotation. + /// A new instance for mocking. + public static MessageDeltaTextAnnotation MessageDeltaTextAnnotation(int index = default, string type = null) + { + return new UnknownMessageDeltaTextAnnotation(index, type, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The file citation information. + /// The text in the message content that needs to be replaced. + /// The start index of this annotation in the content text. + /// The end index of this annotation in the content text. + /// A new instance for mocking. + public static MessageDeltaTextFileCitationAnnotationObject MessageDeltaTextFileCitationAnnotationObject(int index = default, MessageDeltaTextFileCitationAnnotation fileCitation = null, string text = null, int? startIndex = null, int? endIndex = null) + { + return new MessageDeltaTextFileCitationAnnotationObject( + index, + "file_citation", + serializedAdditionalRawData: null, + fileCitation, + text, + startIndex, + endIndex); + } + + /// Initializes a new instance of . + /// The ID of the specific file the citation is from. + /// The specific quote in the cited file. + /// A new instance for mocking. + public static MessageDeltaTextFileCitationAnnotation MessageDeltaTextFileCitationAnnotation(string fileId = null, string quote = null) + { + return new MessageDeltaTextFileCitationAnnotation(fileId, quote, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The file path information. + /// The start index of this annotation in the content text. + /// The end index of this annotation in the content text. + /// The text in the message content that needs to be replaced. + /// A new instance for mocking. + public static MessageDeltaTextFilePathAnnotationObject MessageDeltaTextFilePathAnnotationObject(int index = default, MessageDeltaTextFilePathAnnotation filePath = null, int? startIndex = null, int? endIndex = null, string text = null) + { + return new MessageDeltaTextFilePathAnnotationObject( + index, + "file_path", + serializedAdditionalRawData: null, + filePath, + startIndex, + endIndex, + text); + } + + /// Initializes a new instance of . + /// The file ID for the annotation. + /// A new instance for mocking. + public static MessageDeltaTextFilePathAnnotation MessageDeltaTextFilePathAnnotation(string fileId = null) + { + return new MessageDeltaTextFilePathAnnotation(fileId, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier of the run step, which can be referenced in API endpoints. + /// The object type, which is always `thread.run.step.delta`. + /// The delta containing the fields that have changed on the run step. + /// A new instance for mocking. + public static RunStepDeltaChunk RunStepDeltaChunk(string id = null, RunStepDeltaChunkObject @object = default, RunStepDelta delta = null) + { + return new RunStepDeltaChunk(id, @object, delta, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The details of the run step. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static RunStepDelta RunStepDelta(RunStepDeltaDetail stepDetails = null) + { + return new RunStepDelta(stepDetails, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The message creation data. + /// A new instance for mocking. + public static RunStepDeltaMessageCreation RunStepDeltaMessageCreation(RunStepDeltaMessageCreationObject messageCreation = null) + { + return new RunStepDeltaMessageCreation("message_creation", serializedAdditionalRawData: null, messageCreation); + } + + /// Initializes a new instance of . + /// The ID of the newly-created message. + /// A new instance for mocking. + public static RunStepDeltaMessageCreationObject RunStepDeltaMessageCreationObject(string messageId = null) + { + return new RunStepDeltaMessageCreationObject(messageId, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The collection of tool calls for the tool call detail item. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + /// A new instance for mocking. + public static RunStepDeltaToolCallObject RunStepDeltaToolCallObject(IEnumerable toolCalls = null) + { + toolCalls ??= new List(); + + return new RunStepDeltaToolCallObject("tool_calls", serializedAdditionalRawData: null, toolCalls?.ToList()); + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// A new instance for mocking. + public static RunStepDeltaToolCall RunStepDeltaToolCall(int index = default, string id = null, string type = null) + { + return new UnknownRunStepDeltaToolCall(index, id, type, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The function data for the tool call. + /// A new instance for mocking. + public static RunStepDeltaFunctionToolCall RunStepDeltaFunctionToolCall(int index = default, string id = null, RunStepDeltaFunction function = null) + { + return new RunStepDeltaFunctionToolCall(index, id, "function", serializedAdditionalRawData: null, function); + } + + /// Initializes a new instance of . + /// The name of the function. + /// The arguments passed to the function as input. + /// The output of the function, null if outputs have not yet been submitted. + /// A new instance for mocking. + public static RunStepDeltaFunction RunStepDeltaFunction(string name = null, string arguments = null, string output = null) + { + return new RunStepDeltaFunction(name, arguments, output, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// Reserved for future use. + /// A new instance for mocking. + public static RunStepDeltaFileSearchToolCall RunStepDeltaFileSearchToolCall(int index = default, string id = null, IReadOnlyDictionary fileSearch = null) + { + fileSearch ??= new Dictionary(); + + return new RunStepDeltaFileSearchToolCall(index, id, "file_search", serializedAdditionalRawData: null, fileSearch); + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The Code Interpreter data for the tool call. + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterToolCall RunStepDeltaCodeInterpreterToolCall(int index = default, string id = null, RunStepDeltaCodeInterpreterDetailItemObject codeInterpreter = null) + { + return new RunStepDeltaCodeInterpreterToolCall(index, id, "code_interpreter", serializedAdditionalRawData: null, codeInterpreter); + } + + /// Initializes a new instance of . + /// The input into the Code Interpreter tool call. + /// + /// The outputs from the Code Interpreter tool call. Code Interpreter can output one or more + /// items, including text (`logs`) or images (`image`). Each of these are represented by a + /// different object type. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterDetailItemObject RunStepDeltaCodeInterpreterDetailItemObject(string input = null, IEnumerable outputs = null) + { + outputs ??= new List(); + + return new RunStepDeltaCodeInterpreterDetailItemObject(input, outputs?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The type of the streaming run step tool call's Code Interpreter output. + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterOutput RunStepDeltaCodeInterpreterOutput(int index = default, string type = null) + { + return new UnknownRunStepDeltaCodeInterpreterOutput(index, type, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The text output from the Code Interpreter tool call. + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterLogOutput RunStepDeltaCodeInterpreterLogOutput(int index = default, string logs = null) + { + return new RunStepDeltaCodeInterpreterLogOutput(index, "logs", serializedAdditionalRawData: null, logs); + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The image data for the Code Interpreter tool call output. + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterImageOutput RunStepDeltaCodeInterpreterImageOutput(int index = default, RunStepDeltaCodeInterpreterImageOutputObject image = null) + { + return new RunStepDeltaCodeInterpreterImageOutput(index, "image", serializedAdditionalRawData: null, image); + } + + /// Initializes a new instance of . + /// The file ID for the image. + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterImageOutputObject RunStepDeltaCodeInterpreterImageOutputObject(string fileId = null) + { + return new RunStepDeltaCodeInterpreterImageOutputObject(fileId, serializedAdditionalRawData: null); + } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.Serialization.cs new file mode 100644 index 000000000000..da652aaf0b45 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class AssistantsNamedToolChoice : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AssistantsNamedToolChoice)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (Optional.IsDefined(Function)) + { + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AssistantsNamedToolChoice 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(AssistantsNamedToolChoice)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAssistantsNamedToolChoice(document.RootElement, options); + } + + internal static AssistantsNamedToolChoice DeserializeAssistantsNamedToolChoice(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AssistantsNamedToolChoiceType type = default; + FunctionName function = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new AssistantsNamedToolChoiceType(property.Value.GetString()); + continue; + } + if (property.NameEquals("function"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + function = FunctionName.DeserializeFunctionName(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AssistantsNamedToolChoice(type, function, serializedAdditionalRawData); + } + + 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(AssistantsNamedToolChoice)} does not support writing '{options.Format}' format."); + } + } + + AssistantsNamedToolChoice 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 DeserializeAssistantsNamedToolChoice(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssistantsNamedToolChoice)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AssistantsNamedToolChoice FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAssistantsNamedToolChoice(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.cs new file mode 100644 index 000000000000..b0da555fe4a1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Specifies a tool the model should use. Use to force the model to call a specific tool. + public partial class AssistantsNamedToolChoice + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// the type of tool. If type is `function`, the function name must be set. + public AssistantsNamedToolChoice(AssistantsNamedToolChoiceType type) + { + Type = type; + } + + /// Initializes a new instance of . + /// the type of tool. If type is `function`, the function name must be set. + /// The name of the function to call. + /// Keeps track of any properties unknown to the library. + internal AssistantsNamedToolChoice(AssistantsNamedToolChoiceType type, FunctionName function, IDictionary serializedAdditionalRawData) + { + Type = type; + Function = function; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AssistantsNamedToolChoice() + { + } + + /// the type of tool. If type is `function`, the function name must be set. + public AssistantsNamedToolChoiceType Type { get; set; } + /// The name of the function to call. + public FunctionName Function { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoiceType.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoiceType.cs new file mode 100644 index 000000000000..0d049b86843b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoiceType.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Available tool types for assistants named tools. + public readonly partial struct AssistantsNamedToolChoiceType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AssistantsNamedToolChoiceType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FunctionValue = "function"; + private const string CodeInterpreterValue = "code_interpreter"; + private const string FileSearchValue = "file_search"; + + /// Tool type `function`. + public static AssistantsNamedToolChoiceType Function { get; } = new AssistantsNamedToolChoiceType(FunctionValue); + /// Tool type `code_interpreter`. + public static AssistantsNamedToolChoiceType CodeInterpreter { get; } = new AssistantsNamedToolChoiceType(CodeInterpreterValue); + /// Tool type `file_search`. + public static AssistantsNamedToolChoiceType FileSearch { get; } = new AssistantsNamedToolChoiceType(FileSearchValue); + /// Determines if two values are the same. + public static bool operator ==(AssistantsNamedToolChoiceType left, AssistantsNamedToolChoiceType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AssistantsNamedToolChoiceType left, AssistantsNamedToolChoiceType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AssistantsNamedToolChoiceType(string value) => new AssistantsNamedToolChoiceType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AssistantsNamedToolChoiceType other && Equals(other); + /// + public bool Equals(AssistantsNamedToolChoiceType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.Serialization.cs new file mode 100644 index 000000000000..152d0868305a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.Serialization.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class CodeInterpreterToolResource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CodeInterpreterToolResource)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CodeInterpreterToolResource 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(CodeInterpreterToolResource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCodeInterpreterToolResource(document.RootElement, options); + } + + internal static CodeInterpreterToolResource DeserializeCodeInterpreterToolResource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList fileIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_ids"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + fileIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CodeInterpreterToolResource(fileIds, serializedAdditionalRawData); + } + + 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(CodeInterpreterToolResource)} does not support writing '{options.Format}' format."); + } + } + + CodeInterpreterToolResource 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 DeserializeCodeInterpreterToolResource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CodeInterpreterToolResource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CodeInterpreterToolResource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCodeInterpreterToolResource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.cs new file mode 100644 index 000000000000..a0a185a491bc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A set of resources that are used by the `code_interpreter` tool. + public partial class CodeInterpreterToolResource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + /// is null. + internal CodeInterpreterToolResource(IEnumerable fileIds) + { + Argument.AssertNotNull(fileIds, nameof(fileIds)); + + FileIds = fileIds.ToList(); + } + + /// Initializes a new instance of . + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + /// Keeps track of any properties unknown to the library. + internal CodeInterpreterToolResource(IReadOnlyList fileIds, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CodeInterpreterToolResource() + { + } + + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + public IReadOnlyList FileIds { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.Serialization.cs index e91fb2d48f48..f45781b4b335 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.Serialization.cs @@ -35,23 +35,164 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea } if (Optional.IsDefined(OverrideModelName)) { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(OverrideModelName); + if (OverrideModelName != null) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(OverrideModelName); + } + else + { + writer.WriteNull("model"); + } } if (Optional.IsDefined(OverrideInstructions)) { - writer.WritePropertyName("instructions"u8); - writer.WriteStringValue(OverrideInstructions); + if (OverrideInstructions != null) + { + writer.WritePropertyName("instructions"u8); + writer.WriteStringValue(OverrideInstructions); + } + else + { + writer.WriteNull("instructions"); + } } if (Optional.IsCollectionDefined(OverrideTools)) { - writer.WritePropertyName("tools"u8); - writer.WriteStartArray(); - foreach (var item in OverrideTools) + if (OverrideTools != null) + { + writer.WritePropertyName("tools"u8); + writer.WriteStartArray(); + foreach (var item in OverrideTools) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("tools"); + } + } + if (Optional.IsDefined(ParallelToolCalls)) + { + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(ParallelToolCalls.Value); + } + if (Optional.IsDefined(ToolResources)) + { + if (ToolResources != null) { - writer.WriteObjectValue(item, options); + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } + } + if (Optional.IsDefined(Stream)) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(Stream.Value); + } + if (Optional.IsDefined(Temperature)) + { + if (Temperature != null) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + } + if (Optional.IsDefined(TopP)) + { + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + } + if (Optional.IsDefined(MaxPromptTokens)) + { + if (MaxPromptTokens != null) + { + writer.WritePropertyName("max_prompt_tokens"u8); + writer.WriteNumberValue(MaxPromptTokens.Value); + } + else + { + writer.WriteNull("max_prompt_tokens"); + } + } + if (Optional.IsDefined(MaxCompletionTokens)) + { + if (MaxCompletionTokens != null) + { + writer.WritePropertyName("max_completion_tokens"u8); + writer.WriteNumberValue(MaxCompletionTokens.Value); + } + else + { + writer.WriteNull("max_completion_tokens"); + } + } + if (Optional.IsDefined(TruncationStrategy)) + { + if (TruncationStrategy != null) + { + writer.WritePropertyName("truncation_strategy"u8); + writer.WriteObjectValue(TruncationStrategy, options); + } + else + { + writer.WriteNull("truncation_strategy"); + } + } + if (Optional.IsDefined(ToolChoice)) + { + if (ToolChoice != null) + { + writer.WritePropertyName("tool_choice"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ToolChoice); +#else + using (JsonDocument document = JsonDocument.Parse(ToolChoice)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("tool_choice"); + } + } + if (Optional.IsDefined(ResponseFormat)) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); } - writer.WriteEndArray(); } if (Optional.IsCollectionDefined(Metadata)) { @@ -114,6 +255,16 @@ internal static CreateAndRunThreadOptions DeserializeCreateAndRunThreadOptions(J string model = default; string instructions = default; IList tools = default; + bool? parallelToolCalls = default; + UpdateToolResourcesOptions toolResources = default; + bool? stream = default; + float? temperature = default; + float? topP = default; + int? maxPromptTokens = default; + int? maxCompletionTokens = default; + TruncationObject truncationStrategy = default; + BinaryData toolChoice = default; + BinaryData responseFormat = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -135,11 +286,21 @@ internal static CreateAndRunThreadOptions DeserializeCreateAndRunThreadOptions(J } if (property.NameEquals("model"u8)) { + if (property.Value.ValueKind == JsonValueKind.Null) + { + model = null; + continue; + } model = property.Value.GetString(); continue; } if (property.NameEquals("instructions"u8)) { + if (property.Value.ValueKind == JsonValueKind.Null) + { + instructions = null; + continue; + } instructions = property.Value.GetString(); continue; } @@ -157,6 +318,104 @@ internal static CreateAndRunThreadOptions DeserializeCreateAndRunThreadOptions(J tools = array; continue; } + if (property.NameEquals("parallel_tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parallelToolCalls = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("tool_resources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolResources = null; + continue; + } + toolResources = UpdateToolResourcesOptions.DeserializeUpdateToolResourcesOptions(property.Value, options); + continue; + } + if (property.NameEquals("stream"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stream = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("max_prompt_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxPromptTokens = null; + continue; + } + maxPromptTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_completion_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxCompletionTokens = null; + continue; + } + maxCompletionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("truncation_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + truncationStrategy = null; + continue; + } + truncationStrategy = TruncationObject.DeserializeTruncationObject(property.Value, options); + continue; + } + if (property.NameEquals("tool_choice"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolChoice = null; + continue; + } + toolChoice = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; + } + responseFormat = BinaryData.FromString(property.Value.GetRawText()); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -183,6 +442,16 @@ internal static CreateAndRunThreadOptions DeserializeCreateAndRunThreadOptions(J model, instructions, tools ?? new ChangeTrackingList(), + parallelToolCalls, + toolResources, + stream, + temperature, + topP, + maxPromptTokens, + maxCompletionTokens, + truncationStrategy, + toolChoice, + responseFormat, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.cs index cf9c983195f7..16f117a439d8 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.cs @@ -59,23 +59,63 @@ public CreateAndRunThreadOptions(string assistantId) /// Initializes a new instance of . /// The ID of the assistant for which the thread should be created. - /// The details used to create the new thread. + /// The details used to create the new thread. If no thread is provided, an empty one will be created. /// The overridden model that the assistant should use to run the thread. /// The overridden system instructions the assistant should use to run the thread. /// /// The overridden list of enabled tools the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// + /// Whether to enable parallel function calling during tool use. + /// Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens + /// specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Specifies the format that the model must output. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal CreateAndRunThreadOptions(string assistantId, AssistantThreadCreationOptions thread, string overrideModelName, string overrideInstructions, IList overrideTools, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal CreateAndRunThreadOptions(string assistantId, AssistantThreadCreationOptions thread, string overrideModelName, string overrideInstructions, IList overrideTools, bool? parallelToolCalls, UpdateToolResourcesOptions toolResources, bool? stream, float? temperature, float? topP, int? maxPromptTokens, int? maxCompletionTokens, TruncationObject truncationStrategy, BinaryData toolChoice, BinaryData responseFormat, IDictionary metadata, IDictionary serializedAdditionalRawData) { AssistantId = assistantId; Thread = thread; OverrideModelName = overrideModelName; OverrideInstructions = overrideInstructions; OverrideTools = overrideTools; + ParallelToolCalls = parallelToolCalls; + ToolResources = toolResources; + Stream = stream; + Temperature = temperature; + TopP = topP; + MaxPromptTokens = maxPromptTokens; + MaxCompletionTokens = maxCompletionTokens; + TruncationStrategy = truncationStrategy; + ToolChoice = toolChoice; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -87,7 +127,7 @@ internal CreateAndRunThreadOptions() /// The ID of the assistant for which the thread should be created. public string AssistantId { get; } - /// The details used to create the new thread. + /// The details used to create the new thread. If no thread is provided, an empty one will be created. public AssistantThreadCreationOptions Thread { get; set; } /// The overridden model that the assistant should use to run the thread. public string OverrideModelName { get; set; } @@ -96,9 +136,135 @@ internal CreateAndRunThreadOptions() /// /// The overridden list of enabled tools the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . + /// + public IList OverrideTools { get; set; } + /// Whether to enable parallel function calling during tool use. + public bool? ParallelToolCalls { get; set; } + /// Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + public UpdateToolResourcesOptions ToolResources { get; set; } + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + public bool? Stream { get; set; } + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + public float? Temperature { get; set; } + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + public float? TopP { get; set; } + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + public int? MaxPromptTokens { get; set; } + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens + /// specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + public int? MaxCompletionTokens { get; set; } + /// The strategy to use for dropping messages as the context windows moves forward. + public TruncationObject TruncationStrategy { get; set; } + /// + /// Controls whether or not and which tool is called by the model. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ToolChoice { get; set; } + /// + /// Specifies the format that the model must output. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// /// - public IList OverrideTools { get; } + public BinaryData ResponseFormat { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.Serialization.cs new file mode 100644 index 000000000000..887cb1e943d8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class CreateCodeInterpreterToolResourceOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CreateCodeInterpreterToolResourceOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsCollectionDefined(FileIds)) + { + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CreateCodeInterpreterToolResourceOptions 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(CreateCodeInterpreterToolResourceOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCreateCodeInterpreterToolResourceOptions(document.RootElement, options); + } + + internal static CreateCodeInterpreterToolResourceOptions DeserializeCreateCodeInterpreterToolResourceOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList fileIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_ids"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + fileIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CreateCodeInterpreterToolResourceOptions(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + 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(CreateCodeInterpreterToolResourceOptions)} does not support writing '{options.Format}' format."); + } + } + + CreateCodeInterpreterToolResourceOptions 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 DeserializeCreateCodeInterpreterToolResourceOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CreateCodeInterpreterToolResourceOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CreateCodeInterpreterToolResourceOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCreateCodeInterpreterToolResourceOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.cs new file mode 100644 index 000000000000..97be44a94098 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A set of resources that will be used by the `code_interpreter` tool. Request object. + public partial class CreateCodeInterpreterToolResourceOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public CreateCodeInterpreterToolResourceOptions() + { + FileIds = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// A list of file IDs made available to the `code_interpreter` tool. + /// Keeps track of any properties unknown to the library. + internal CreateCodeInterpreterToolResourceOptions(IList fileIds, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A list of file IDs made available to the `code_interpreter` tool. + public IList FileIds { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.Serialization.cs similarity index 60% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.Serialization.cs index 8ec0eefb2fc4..758a3da794aa 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.Serialization.cs @@ -13,33 +13,28 @@ namespace Azure.AI.OpenAI.Assistants { - public partial class ThreadInitializationMessage : IUtf8JsonSerializable, IJsonModel + public partial class CreateFileSearchToolResourceVectorStoreOptions : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(ThreadInitializationMessage)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(CreateFileSearchToolResourceVectorStoreOptions)} does not support writing '{format}' format."); } writer.WriteStartObject(); - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role.ToString()); - writer.WritePropertyName("content"u8); - writer.WriteStringValue(Content); - if (Optional.IsCollectionDefined(FileIds)) + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) { - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); + writer.WriteStringValue(item); } + writer.WriteEndArray(); + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); if (Optional.IsCollectionDefined(Metadata)) { if (Metadata != null) @@ -76,19 +71,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR writer.WriteEndObject(); } - ThreadInitializationMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + CreateFileSearchToolResourceVectorStoreOptions 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(ThreadInitializationMessage)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(CreateFileSearchToolResourceVectorStoreOptions)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeThreadInitializationMessage(document.RootElement, options); + return DeserializeCreateFileSearchToolResourceVectorStoreOptions(document.RootElement, options); } - internal static ThreadInitializationMessage DeserializeThreadInitializationMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static CreateFileSearchToolResourceVectorStoreOptions DeserializeCreateFileSearchToolResourceVectorStoreOptions(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -96,30 +91,15 @@ internal static ThreadInitializationMessage DeserializeThreadInitializationMessa { return null; } - MessageRole role = default; - string content = default; IList fileIds = default; + VectorStoreChunkingStrategyRequest chunkingStrategy = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("role"u8)) - { - role = new MessageRole(property.Value.GetString()); - continue; - } - if (property.NameEquals("content"u8)) - { - content = property.Value.GetString(); - continue; - } if (property.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } List array = new List(); foreach (var item in property.Value.EnumerateArray()) { @@ -128,6 +108,11 @@ internal static ThreadInitializationMessage DeserializeThreadInitializationMessa fileIds = array; continue; } + if (property.NameEquals("chunking_strategy"u8)) + { + chunkingStrategy = VectorStoreChunkingStrategyRequest.DeserializeVectorStoreChunkingStrategyRequest(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -148,46 +133,46 @@ internal static ThreadInitializationMessage DeserializeThreadInitializationMessa } } serializedAdditionalRawData = rawDataDictionary; - return new ThreadInitializationMessage(role, content, fileIds ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new CreateFileSearchToolResourceVectorStoreOptions(fileIds, chunkingStrategy, metadata ?? new ChangeTrackingDictionary(), 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(ThreadInitializationMessage)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(CreateFileSearchToolResourceVectorStoreOptions)} does not support writing '{options.Format}' format."); } } - ThreadInitializationMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + CreateFileSearchToolResourceVectorStoreOptions 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 DeserializeThreadInitializationMessage(document.RootElement, options); + return DeserializeCreateFileSearchToolResourceVectorStoreOptions(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ThreadInitializationMessage)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(CreateFileSearchToolResourceVectorStoreOptions)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static ThreadInitializationMessage FromResponse(Response response) + internal static CreateFileSearchToolResourceVectorStoreOptions FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeThreadInitializationMessage(document.RootElement); + return DeserializeCreateFileSearchToolResourceVectorStoreOptions(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.cs new file mode 100644 index 000000000000..cac5e291a8a8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// File IDs associated to the vector store to be passed to the helper. + public partial class CreateFileSearchToolResourceVectorStoreOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// or is null. + public CreateFileSearchToolResourceVectorStoreOptions(IEnumerable fileIds, VectorStoreChunkingStrategyRequest chunkingStrategy) + { + Argument.AssertNotNull(fileIds, nameof(fileIds)); + Argument.AssertNotNull(chunkingStrategy, nameof(chunkingStrategy)); + + FileIds = fileIds.ToList(); + ChunkingStrategy = chunkingStrategy; + Metadata = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Keeps track of any properties unknown to the library. + internal CreateFileSearchToolResourceVectorStoreOptions(IList fileIds, VectorStoreChunkingStrategyRequest chunkingStrategy, IDictionary metadata, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + ChunkingStrategy = chunkingStrategy; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CreateFileSearchToolResourceVectorStoreOptions() + { + } + + /// A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + public IList FileIds { get; } + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public VectorStoreChunkingStrategyRequest ChunkingStrategy { get; } + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + public IDictionary Metadata { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.Serialization.cs index 1e4243ff8d01..ee2e77118f4c 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.Serialization.cs @@ -64,6 +64,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter writer.WriteNull("additional_instructions"); } } + if (Optional.IsCollectionDefined(AdditionalMessages)) + { + if (AdditionalMessages != null) + { + writer.WritePropertyName("additional_messages"u8); + writer.WriteStartArray(); + foreach (var item in AdditionalMessages) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("additional_messages"); + } + } if (Optional.IsCollectionDefined(OverrideTools)) { if (OverrideTools != null) @@ -81,6 +98,114 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter writer.WriteNull("tools"); } } + if (Optional.IsDefined(ParallelToolCalls)) + { + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(ParallelToolCalls.Value); + } + if (Optional.IsDefined(Stream)) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(Stream.Value); + } + if (Optional.IsDefined(Temperature)) + { + if (Temperature != null) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + } + if (Optional.IsDefined(TopP)) + { + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + } + if (Optional.IsDefined(MaxPromptTokens)) + { + if (MaxPromptTokens != null) + { + writer.WritePropertyName("max_prompt_tokens"u8); + writer.WriteNumberValue(MaxPromptTokens.Value); + } + else + { + writer.WriteNull("max_prompt_tokens"); + } + } + if (Optional.IsDefined(MaxCompletionTokens)) + { + if (MaxCompletionTokens != null) + { + writer.WritePropertyName("max_completion_tokens"u8); + writer.WriteNumberValue(MaxCompletionTokens.Value); + } + else + { + writer.WriteNull("max_completion_tokens"); + } + } + if (Optional.IsDefined(TruncationStrategy)) + { + if (TruncationStrategy != null) + { + writer.WritePropertyName("truncation_strategy"u8); + writer.WriteObjectValue(TruncationStrategy, options); + } + else + { + writer.WriteNull("truncation_strategy"); + } + } + if (Optional.IsDefined(ToolChoice)) + { + if (ToolChoice != null) + { + writer.WritePropertyName("tool_choice"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ToolChoice); +#else + using (JsonDocument document = JsonDocument.Parse(ToolChoice)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("tool_choice"); + } + } + if (Optional.IsDefined(ResponseFormat)) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); + } + } if (Optional.IsCollectionDefined(Metadata)) { if (Metadata != null) @@ -141,7 +266,17 @@ internal static CreateRunOptions DeserializeCreateRunOptions(JsonElement element string model = default; string instructions = default; string additionalInstructions = default; + IList additionalMessages = default; IList tools = default; + bool? parallelToolCalls = default; + bool? stream = default; + float? temperature = default; + float? topP = default; + int? maxPromptTokens = default; + int? maxCompletionTokens = default; + TruncationObject truncationStrategy = default; + BinaryData toolChoice = default; + BinaryData responseFormat = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -182,6 +317,20 @@ internal static CreateRunOptions DeserializeCreateRunOptions(JsonElement element additionalInstructions = property.Value.GetString(); continue; } + if (property.NameEquals("additional_messages"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ThreadMessage.DeserializeThreadMessage(item, options)); + } + additionalMessages = array; + continue; + } if (property.NameEquals("tools"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -196,6 +345,94 @@ internal static CreateRunOptions DeserializeCreateRunOptions(JsonElement element tools = array; continue; } + if (property.NameEquals("parallel_tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parallelToolCalls = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stream"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stream = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("max_prompt_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxPromptTokens = null; + continue; + } + maxPromptTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_completion_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxCompletionTokens = null; + continue; + } + maxCompletionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("truncation_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + truncationStrategy = null; + continue; + } + truncationStrategy = TruncationObject.DeserializeTruncationObject(property.Value, options); + continue; + } + if (property.NameEquals("tool_choice"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolChoice = null; + continue; + } + toolChoice = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; + } + responseFormat = BinaryData.FromString(property.Value.GetRawText()); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -221,7 +458,17 @@ internal static CreateRunOptions DeserializeCreateRunOptions(JsonElement element model, instructions, additionalInstructions, + additionalMessages ?? new ChangeTrackingList(), tools ?? new ChangeTrackingList(), + parallelToolCalls, + stream, + temperature, + topP, + maxPromptTokens, + maxCompletionTokens, + truncationStrategy, + toolChoice, + responseFormat, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.cs index 1c307b753523..b8a9e8507c50 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.cs @@ -53,6 +53,7 @@ public CreateRunOptions(string assistantId) Argument.AssertNotNull(assistantId, nameof(assistantId)); AssistantId = assistantId; + AdditionalMessages = new ChangeTrackingList(); OverrideTools = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } @@ -65,20 +66,60 @@ public CreateRunOptions(string assistantId) /// Additional instructions to append at the end of the instructions for the run. This is useful for modifying the behavior /// on a per-run basis without overriding other instructions. /// + /// Adds additional messages to the thread before creating the run. /// /// The overridden list of enabled tools that the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// + /// Whether to enable parallel function calling during tool use. + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort + /// to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of + /// completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Specifies the format that the model must output. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal CreateRunOptions(string assistantId, string overrideModelName, string overrideInstructions, string additionalInstructions, IList overrideTools, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal CreateRunOptions(string assistantId, string overrideModelName, string overrideInstructions, string additionalInstructions, IList additionalMessages, IList overrideTools, bool? parallelToolCalls, bool? stream, float? temperature, float? topP, int? maxPromptTokens, int? maxCompletionTokens, TruncationObject truncationStrategy, BinaryData toolChoice, BinaryData responseFormat, IDictionary metadata, IDictionary serializedAdditionalRawData) { AssistantId = assistantId; OverrideModelName = overrideModelName; OverrideInstructions = overrideInstructions; AdditionalInstructions = additionalInstructions; + AdditionalMessages = additionalMessages; OverrideTools = overrideTools; + ParallelToolCalls = parallelToolCalls; + Stream = stream; + Temperature = temperature; + TopP = topP; + MaxPromptTokens = maxPromptTokens; + MaxCompletionTokens = maxCompletionTokens; + TruncationStrategy = truncationStrategy; + ToolChoice = toolChoice; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -99,12 +140,138 @@ internal CreateRunOptions() /// on a per-run basis without overriding other instructions. /// public string AdditionalInstructions { get; set; } + /// Adds additional messages to the thread before creating the run. + public IList AdditionalMessages { get; set; } /// /// The overridden list of enabled tools that the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IList OverrideTools { get; set; } + /// Whether to enable parallel function calling during tool use. + public bool? ParallelToolCalls { get; set; } + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + public bool? Stream { get; set; } + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + public float? Temperature { get; set; } + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + public float? TopP { get; set; } + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + public int? MaxPromptTokens { get; set; } + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort + /// to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of + /// completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + public int? MaxCompletionTokens { get; set; } + /// The strategy to use for dropping messages as the context windows moves forward. + public TruncationObject TruncationStrategy { get; set; } + /// + /// Controls whether or not and which tool is called by the model. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ToolChoice { get; set; } + /// + /// Specifies the format that the model must output. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ResponseFormat { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.Serialization.cs new file mode 100644 index 000000000000..228c9350b244 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.Serialization.cs @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class CreateToolResourcesOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CreateToolResourcesOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(CodeInterpreter)) + { + writer.WritePropertyName("code_interpreter"u8); + writer.WriteObjectValue(CodeInterpreter, options); + } + if (Optional.IsDefined(FileSearch)) + { + writer.WritePropertyName("file_search"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(FileSearch); +#else + using (JsonDocument document = JsonDocument.Parse(FileSearch)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CreateToolResourcesOptions 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(CreateToolResourcesOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCreateToolResourcesOptions(document.RootElement, options); + } + + internal static CreateToolResourcesOptions DeserializeCreateToolResourcesOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CreateCodeInterpreterToolResourceOptions codeInterpreter = default; + BinaryData fileSearch = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code_interpreter"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + codeInterpreter = CreateCodeInterpreterToolResourceOptions.DeserializeCreateCodeInterpreterToolResourceOptions(property.Value, options); + continue; + } + if (property.NameEquals("file_search"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileSearch = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CreateToolResourcesOptions(codeInterpreter, fileSearch, serializedAdditionalRawData); + } + + 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(CreateToolResourcesOptions)} does not support writing '{options.Format}' format."); + } + } + + CreateToolResourcesOptions 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 DeserializeCreateToolResourcesOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CreateToolResourcesOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CreateToolResourcesOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCreateToolResourcesOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.cs new file mode 100644 index 000000000000..796bdccc21f0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// Request object. A set of resources that are used by the assistant's tools. The resources are specific to the + /// type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` + /// tool requires a list of vector store IDs. + /// + public partial class CreateToolResourcesOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public CreateToolResourcesOptions() + { + } + + /// Initializes a new instance of . + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + /// A list of vector stores or their IDs made available to the `file_search` tool. + /// Keeps track of any properties unknown to the library. + internal CreateToolResourcesOptions(CreateCodeInterpreterToolResourceOptions codeInterpreter, BinaryData fileSearch, IDictionary serializedAdditionalRawData) + { + CodeInterpreter = codeInterpreter; + FileSearch = fileSearch; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + public CreateCodeInterpreterToolResourceOptions CodeInterpreter { get; set; } + /// + /// A list of vector stores or their IDs made available to the `file_search` tool. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// where T is of type + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData FileSearch { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.Serialization.cs new file mode 100644 index 000000000000..0afaf2dea1a2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class CreateVectorStoreFileBatchRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CreateVectorStoreFileBatchRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(ChunkingStrategy)) + { + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CreateVectorStoreFileBatchRequest 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(CreateVectorStoreFileBatchRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCreateVectorStoreFileBatchRequest(document.RootElement, options); + } + + internal static CreateVectorStoreFileBatchRequest DeserializeCreateVectorStoreFileBatchRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList fileIds = default; + VectorStoreChunkingStrategyRequest chunkingStrategy = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_ids"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + fileIds = array; + continue; + } + if (property.NameEquals("chunking_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + chunkingStrategy = VectorStoreChunkingStrategyRequest.DeserializeVectorStoreChunkingStrategyRequest(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CreateVectorStoreFileBatchRequest(fileIds, chunkingStrategy, serializedAdditionalRawData); + } + + 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(CreateVectorStoreFileBatchRequest)} does not support writing '{options.Format}' format."); + } + } + + CreateVectorStoreFileBatchRequest 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 DeserializeCreateVectorStoreFileBatchRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CreateVectorStoreFileBatchRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CreateVectorStoreFileBatchRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCreateVectorStoreFileBatchRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.cs new file mode 100644 index 000000000000..ae91f3b2fed8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The CreateVectorStoreFileBatchRequest. + internal partial class CreateVectorStoreFileBatchRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A list of File IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// is null. + internal CreateVectorStoreFileBatchRequest(IEnumerable fileIds) + { + Argument.AssertNotNull(fileIds, nameof(fileIds)); + + FileIds = fileIds.ToList(); + } + + /// Initializes a new instance of . + /// A list of File IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal CreateVectorStoreFileBatchRequest(IReadOnlyList fileIds, VectorStoreChunkingStrategyRequest chunkingStrategy, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + ChunkingStrategy = chunkingStrategy; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CreateVectorStoreFileBatchRequest() + { + } + + /// A list of File IDs that the vector store should use. Useful for tools like `file_search` that can access files. + public IReadOnlyList FileIds { get; } + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public VectorStoreChunkingStrategyRequest ChunkingStrategy { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.Serialization.cs new file mode 100644 index 000000000000..7b1a5bf6ac82 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class CreateVectorStoreFileRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CreateVectorStoreFileRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + if (Optional.IsDefined(ChunkingStrategy)) + { + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CreateVectorStoreFileRequest 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(CreateVectorStoreFileRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCreateVectorStoreFileRequest(document.RootElement, options); + } + + internal static CreateVectorStoreFileRequest DeserializeCreateVectorStoreFileRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + VectorStoreChunkingStrategyRequest chunkingStrategy = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("chunking_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + chunkingStrategy = VectorStoreChunkingStrategyRequest.DeserializeVectorStoreChunkingStrategyRequest(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CreateVectorStoreFileRequest(fileId, chunkingStrategy, serializedAdditionalRawData); + } + + 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(CreateVectorStoreFileRequest)} does not support writing '{options.Format}' format."); + } + } + + CreateVectorStoreFileRequest 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 DeserializeCreateVectorStoreFileRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CreateVectorStoreFileRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CreateVectorStoreFileRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCreateVectorStoreFileRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.cs new file mode 100644 index 000000000000..fdda0a8891d1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The CreateVectorStoreFileRequest. + internal partial class CreateVectorStoreFileRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A File ID that the vector store should use. Useful for tools like `file_search` that can access files. + /// is null. + internal CreateVectorStoreFileRequest(string fileId) + { + Argument.AssertNotNull(fileId, nameof(fileId)); + + FileId = fileId; + } + + /// Initializes a new instance of . + /// A File ID that the vector store should use. Useful for tools like `file_search` that can access files. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal CreateVectorStoreFileRequest(string fileId, VectorStoreChunkingStrategyRequest chunkingStrategy, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + ChunkingStrategy = chunkingStrategy; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CreateVectorStoreFileRequest() + { + } + + /// A File ID that the vector store should use. Useful for tools like `file_search` that can access files. + public string FileId { get; } + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public VectorStoreChunkingStrategyRequest ChunkingStrategy { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/DoneEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/DoneEvent.cs new file mode 100644 index 000000000000..d59d8966c668 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/DoneEvent.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Terminal event indicating the successful end of a stream. + public readonly partial struct DoneEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DoneEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string DoneValue = "done"; + + /// Event sent when the stream is done. + public static DoneEvent Done { get; } = new DoneEvent(DoneValue); + /// Determines if two values are the same. + public static bool operator ==(DoneEvent left, DoneEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DoneEvent left, DoneEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DoneEvent(string value) => new DoneEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DoneEvent other && Equals(other); + /// + public bool Equals(DoneEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ErrorEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ErrorEvent.cs new file mode 100644 index 000000000000..3a26ca078a2f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ErrorEvent.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Terminal event indicating a server side error while streaming. + public readonly partial struct ErrorEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ErrorEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ErrorValue = "error"; + + /// Event sent when an error occurs, such as an internal server error or a timeout. + public static ErrorEvent Error { get; } = new ErrorEvent(ErrorValue); + /// Determines if two values are the same. + public static bool operator ==(ErrorEvent left, ErrorEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ErrorEvent left, ErrorEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ErrorEvent(string value) => new ErrorEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ErrorEvent other && Equals(other); + /// + public bool Equals(ErrorEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.Serialization.cs new file mode 100644 index 000000000000..044e4cfb677f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class FileSearchToolDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(FileSearchToolDefinition)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(FileSearch)) + { + writer.WritePropertyName("file_search"u8); + writer.WriteObjectValue(FileSearch, options); + } + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + FileSearchToolDefinition 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(FileSearchToolDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileSearchToolDefinition(document.RootElement, options); + } + + internal static FileSearchToolDefinition DeserializeFileSearchToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + FileSearchToolDefinitionDetails fileSearch = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_search"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileSearch = FileSearchToolDefinitionDetails.DeserializeFileSearchToolDefinitionDetails(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileSearchToolDefinition(type, serializedAdditionalRawData, fileSearch); + } + + 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(FileSearchToolDefinition)} does not support writing '{options.Format}' format."); + } + } + + FileSearchToolDefinition 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 DeserializeFileSearchToolDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileSearchToolDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new FileSearchToolDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFileSearchToolDefinition(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.cs new file mode 100644 index 000000000000..e68594b90832 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.cs @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The input definition information for a file search tool as used to configure an assistant. + public partial class FileSearchToolDefinition : ToolDefinition + { + /// Initializes a new instance of . + public FileSearchToolDefinition() + { + Type = "file_search"; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + /// Options overrides for the file search tool. + internal FileSearchToolDefinition(string type, IDictionary serializedAdditionalRawData, FileSearchToolDefinitionDetails fileSearch) : base(type, serializedAdditionalRawData) + { + FileSearch = fileSearch; + } + + /// Options overrides for the file search tool. + public FileSearchToolDefinitionDetails FileSearch { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.Serialization.cs new file mode 100644 index 000000000000..e1f77ecfcfbb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class FileSearchToolDefinitionDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(FileSearchToolDefinitionDetails)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(MaxNumResults)) + { + writer.WritePropertyName("max_num_results"u8); + writer.WriteNumberValue(MaxNumResults.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + FileSearchToolDefinitionDetails 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(FileSearchToolDefinitionDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileSearchToolDefinitionDetails(document.RootElement, options); + } + + internal static FileSearchToolDefinitionDetails DeserializeFileSearchToolDefinitionDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? maxNumResults = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("max_num_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxNumResults = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileSearchToolDefinitionDetails(maxNumResults, serializedAdditionalRawData); + } + + 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(FileSearchToolDefinitionDetails)} does not support writing '{options.Format}' format."); + } + } + + FileSearchToolDefinitionDetails 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 DeserializeFileSearchToolDefinitionDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileSearchToolDefinitionDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FileSearchToolDefinitionDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFileSearchToolDefinitionDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.cs new file mode 100644 index 000000000000..019548640805 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Options overrides for the file search tool. + public partial class FileSearchToolDefinitionDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public FileSearchToolDefinitionDetails() + { + } + + /// Initializes a new instance of . + /// + /// The maximum number of results the file search tool should output. The default is 20 for gpt-4* models and 5 for gpt-3.5-turbo. This number should be between 1 and 50 inclusive. + /// + /// Note that the file search tool may output fewer than `max_num_results` results. See the file search tool documentation for more information. + /// + /// Keeps track of any properties unknown to the library. + internal FileSearchToolDefinitionDetails(int? maxNumResults, IDictionary serializedAdditionalRawData) + { + MaxNumResults = maxNumResults; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The maximum number of results the file search tool should output. The default is 20 for gpt-4* models and 5 for gpt-3.5-turbo. This number should be between 1 and 50 inclusive. + /// + /// Note that the file search tool may output fewer than `max_num_results` results. See the file search tool documentation for more information. + /// + public int? MaxNumResults { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.Serialization.cs new file mode 100644 index 000000000000..eeeba6c1ad6f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class FileSearchToolResource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(FileSearchToolResource)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsCollectionDefined(VectorStoreIds)) + { + writer.WritePropertyName("vector_store_ids"u8); + writer.WriteStartArray(); + foreach (var item in VectorStoreIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + FileSearchToolResource 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(FileSearchToolResource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileSearchToolResource(document.RootElement, options); + } + + internal static FileSearchToolResource DeserializeFileSearchToolResource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList vectorStoreIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("vector_store_ids"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorStoreIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileSearchToolResource(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + 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(FileSearchToolResource)} does not support writing '{options.Format}' format."); + } + } + + FileSearchToolResource 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 DeserializeFileSearchToolResource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileSearchToolResource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FileSearchToolResource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFileSearchToolResource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.cs new file mode 100644 index 000000000000..94422e677d08 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A set of resources that are used by the `file_search` tool. + public partial class FileSearchToolResource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal FileSearchToolResource() + { + VectorStoreIds = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// + /// The ID of the vector store attached to this assistant. There can be a maximum of 1 vector + /// store attached to the assistant. + /// + /// Keeps track of any properties unknown to the library. + internal FileSearchToolResource(IReadOnlyList vectorStoreIds, IDictionary serializedAdditionalRawData) + { + VectorStoreIds = vectorStoreIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The ID of the vector store attached to this assistant. There can be a maximum of 1 vector + /// store attached to the assistant. + /// + public IReadOnlyList VectorStoreIds { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileState.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileState.cs new file mode 100644 index 000000000000..47ce58179d3d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileState.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The state of the file. + public readonly partial struct FileState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UploadedValue = "uploaded"; + private const string PendingValue = "pending"; + private const string RunningValue = "running"; + private const string ProcessedValue = "processed"; + private const string ErrorValue = "error"; + private const string DeletingValue = "deleting"; + private const string DeletedValue = "deleted"; + + /// + /// The file has been uploaded but it's not yet processed. This state is not returned by Azure OpenAI and exposed only for + /// compatibility. It can be categorized as an inactive state. + /// + public static FileState Uploaded { get; } = new FileState(UploadedValue); + /// The operation was created and is not queued to be processed in the future. It can be categorized as an inactive state. + public static FileState Pending { get; } = new FileState(PendingValue); + /// The operation has started to be processed. It can be categorized as an active state. + public static FileState Running { get; } = new FileState(RunningValue); + /// The operation has successfully processed and is ready for consumption. It can be categorized as a terminal state. + public static FileState Processed { get; } = new FileState(ProcessedValue); + /// The operation has completed processing with a failure and cannot be further consumed. It can be categorized as a terminal state. + public static FileState Error { get; } = new FileState(ErrorValue); + /// + /// The entity is in the process to be deleted. This state is not returned by Azure OpenAI and exposed only for compatibility. + /// It can be categorized as an active state. + /// + public static FileState Deleting { get; } = new FileState(DeletingValue); + /// + /// The entity has been deleted but may still be referenced by other entities predating the deletion. It can be categorized as a + /// terminal state. + /// + public static FileState Deleted { get; } = new FileState(DeletedValue); + /// Determines if two values are the same. + public static bool operator ==(FileState left, FileState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileState left, FileState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FileState(string value) => new FileState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileState other && Equals(other); + /// + public bool Equals(FileState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.Serialization.cs new file mode 100644 index 000000000000..1af0a6d26063 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class FunctionName : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(FunctionName)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + FunctionName 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(FunctionName)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFunctionName(document.RootElement, options); + } + + internal static FunctionName DeserializeFunctionName(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FunctionName(name, serializedAdditionalRawData); + } + + 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(FunctionName)} does not support writing '{options.Format}' format."); + } + } + + FunctionName 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 DeserializeFunctionName(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FunctionName)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FunctionName FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFunctionName(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.cs new file mode 100644 index 000000000000..70fcf993d4ae --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The function name that will be used, if using the `function` tool. + public partial class FunctionName + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the function to call. + /// is null. + public FunctionName(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + /// Initializes a new instance of . + /// The name of the function to call. + /// Keeps track of any properties unknown to the library. + internal FunctionName(string name, IDictionary serializedAdditionalRawData) + { + Name = name; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FunctionName() + { + } + + /// The name of the function to call. + public string Name { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/IncompleteRunDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/IncompleteRunDetails.cs new file mode 100644 index 000000000000..373733568f34 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/IncompleteRunDetails.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run. + public readonly partial struct IncompleteRunDetails : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public IncompleteRunDetails(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string MaxCompletionTokensValue = "max_completion_tokens"; + private const string MaxPromptTokensValue = "max_prompt_tokens"; + + /// Maximum completion tokens exceeded. + public static IncompleteRunDetails MaxCompletionTokens { get; } = new IncompleteRunDetails(MaxCompletionTokensValue); + /// Maximum prompt tokens exceeded. + public static IncompleteRunDetails MaxPromptTokens { get; } = new IncompleteRunDetails(MaxPromptTokensValue); + /// Determines if two values are the same. + public static bool operator ==(IncompleteRunDetails left, IncompleteRunDetails right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(IncompleteRunDetails left, IncompleteRunDetails right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator IncompleteRunDetails(string value) => new IncompleteRunDetails(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is IncompleteRunDetails other && Equals(other); + /// + public bool Equals(IncompleteRunDetails other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatusObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatusObject.cs deleted file mode 100644 index 5c52700f6c0f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatusObject.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI.Assistants -{ - /// The InternalAssistantFileDeletionStatus_object. - internal readonly partial struct InternalAssistantFileDeletionStatusObject : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public InternalAssistantFileDeletionStatusObject(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string AssistantFileDeletedValue = "assistant.file.deleted"; - - /// assistant.file.deleted. - public static InternalAssistantFileDeletionStatusObject AssistantFileDeleted { get; } = new InternalAssistantFileDeletionStatusObject(AssistantFileDeletedValue); - /// Determines if two values are the same. - public static bool operator ==(InternalAssistantFileDeletionStatusObject left, InternalAssistantFileDeletionStatusObject right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(InternalAssistantFileDeletionStatusObject left, InternalAssistantFileDeletionStatusObject right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator InternalAssistantFileDeletionStatusObject(string value) => new InternalAssistantFileDeletionStatusObject(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalAssistantFileDeletionStatusObject other && Equals(other); - /// - public bool Equals(InternalAssistantFileDeletionStatusObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageImageFileDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageImageFileDetails.cs index eb315c465ad1..89cfab2a18a4 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageImageFileDetails.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageImageFileDetails.cs @@ -48,7 +48,7 @@ internal partial class InternalMessageImageFileDetails /// Initializes a new instance of . /// The ID for the file associated with this image. /// is null. - internal InternalMessageImageFileDetails(string internalDetails) + public InternalMessageImageFileDetails(string internalDetails) { Argument.AssertNotNull(internalDetails, nameof(internalDetails)); @@ -70,6 +70,6 @@ internal InternalMessageImageFileDetails() } /// The ID for the file associated with this image. - public string InternalDetails { get; } + public string InternalDetails { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.Serialization.cs index 29ffc7f46eb7..a181f9527cb5 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.Serialization.cs @@ -74,7 +74,7 @@ internal static InternalMessageTextDetails DeserializeInternalMessageTextDetails return null; } string value = default; - IReadOnlyList annotations = default; + IList annotations = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.cs index 7f6a60a62245..4489c4dd184e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.cs @@ -54,7 +54,7 @@ internal partial class InternalMessageTextDetails /// The available derived classes include and . /// /// or is null. - internal InternalMessageTextDetails(string text, IEnumerable annotations) + public InternalMessageTextDetails(string text, IEnumerable annotations) { Argument.AssertNotNull(text, nameof(text)); Argument.AssertNotNull(annotations, nameof(annotations)); @@ -71,7 +71,7 @@ internal InternalMessageTextDetails(string text, IEnumerable and . /// /// Keeps track of any properties unknown to the library. - internal InternalMessageTextDetails(string text, IReadOnlyList annotations, IDictionary serializedAdditionalRawData) + internal InternalMessageTextDetails(string text, IList annotations, IDictionary serializedAdditionalRawData) { Text = text; Annotations = annotations; @@ -84,12 +84,12 @@ internal InternalMessageTextDetails() } /// The text data. - public string Text { get; } + public string Text { get; set; } /// /// A list of annotations associated with this text. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. /// The available derived classes include and . /// - public IReadOnlyList Annotations { get; } + public IList Annotations { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFileCitationDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFileCitationDetails.cs index 3bbdf07622ce..158100231c04 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFileCitationDetails.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFileCitationDetails.cs @@ -49,7 +49,7 @@ internal partial class InternalMessageTextFileCitationDetails /// The ID of the file associated with this citation. /// The specific quote cited in the associated file. /// or is null. - internal InternalMessageTextFileCitationDetails(string fileId, string quote) + public InternalMessageTextFileCitationDetails(string fileId, string quote) { Argument.AssertNotNull(fileId, nameof(fileId)); Argument.AssertNotNull(quote, nameof(quote)); @@ -75,8 +75,8 @@ internal InternalMessageTextFileCitationDetails() } /// The ID of the file associated with this citation. - public string FileId { get; } + public string FileId { get; set; } /// The specific quote cited in the associated file. - public string Quote { get; } + public string Quote { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFilePathDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFilePathDetails.cs index 4b86d66be5a2..f56d8a2f2cce 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFilePathDetails.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFilePathDetails.cs @@ -48,7 +48,7 @@ internal partial class InternalMessageTextFilePathDetails /// Initializes a new instance of . /// The ID of the specific file that the citation is from. /// is null. - internal InternalMessageTextFilePathDetails(string fileId) + public InternalMessageTextFilePathDetails(string fileId) { Argument.AssertNotNull(fileId, nameof(fileId)); @@ -70,6 +70,6 @@ internal InternalMessageTextFilePathDetails() } /// The ID of the specific file that the citation is from. - public string FileId { get; } + public string FileId { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.Serialization.cs new file mode 100644 index 000000000000..9a30136e04e3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.Serialization.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageAttachment : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageAttachment)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + writer.WritePropertyName("tools"u8); + writer.WriteStartArray(); + foreach (var item in Tools) + { + if (item == null) + { + writer.WriteNullValue(); + continue; + } +#if NET6_0_OR_GREATER + writer.WriteRawValue(item); +#else + using (JsonDocument document = JsonDocument.Parse(item)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageAttachment 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(MessageAttachment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageAttachment(document.RootElement, options); + } + + internal static MessageAttachment DeserializeMessageAttachment(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + IList tools = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("tools"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(BinaryData.FromString(item.GetRawText())); + } + } + tools = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageAttachment(fileId, tools, serializedAdditionalRawData); + } + + 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(MessageAttachment)} does not support writing '{options.Format}' format."); + } + } + + MessageAttachment 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 DeserializeMessageAttachment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageAttachment)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageAttachment FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageAttachment(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.cs new file mode 100644 index 000000000000..f905e2a52576 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// This describes to which tools a file has been attached. + public partial class MessageAttachment + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ID of the file to attach to the message. + /// The tools to add to this file. + /// or is null. + public MessageAttachment(string fileId, IEnumerable tools) + { + Argument.AssertNotNull(fileId, nameof(fileId)); + Argument.AssertNotNull(tools, nameof(tools)); + + FileId = fileId; + Tools = tools.ToList(); + } + + /// Initializes a new instance of . + /// The ID of the file to attach to the message. + /// The tools to add to this file. + /// Keeps track of any properties unknown to the library. + internal MessageAttachment(string fileId, IList tools, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + Tools = tools; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MessageAttachment() + { + } + + /// The ID of the file to attach to the message. + public string FileId { get; set; } + /// + /// The tools to add to this file. + /// + /// To assign an object to the element of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public IList Tools { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.Serialization.cs new file mode 100644 index 000000000000..8fbd90a6237b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDelta : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDelta)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + writer.WritePropertyName("content"u8); + writer.WriteStartArray(); + foreach (var item in Content) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDelta 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(MessageDelta)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDelta(document.RootElement, options); + } + + internal static MessageDelta DeserializeMessageDelta(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageRole role = default; + IReadOnlyList content = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("role"u8)) + { + role = new MessageRole(property.Value.GetString()); + continue; + } + if (property.NameEquals("content"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(MessageDeltaContent.DeserializeMessageDeltaContent(item, options)); + } + content = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDelta(role, content, serializedAdditionalRawData); + } + + 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(MessageDelta)} does not support writing '{options.Format}' format."); + } + } + + MessageDelta 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 DeserializeMessageDelta(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDelta)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDelta FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDelta(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.cs new file mode 100644 index 000000000000..ec114efcb09d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the typed 'delta' payload within a streaming message delta chunk. + public partial class MessageDelta + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The entity that produced the message. + /// + /// The content of the message as an array of text and/or images. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// is null. + internal MessageDelta(MessageRole role, IEnumerable content) + { + Argument.AssertNotNull(content, nameof(content)); + + Role = role; + Content = content.ToList(); + } + + /// Initializes a new instance of . + /// The entity that produced the message. + /// + /// The content of the message as an array of text and/or images. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal MessageDelta(MessageRole role, IReadOnlyList content, IDictionary serializedAdditionalRawData) + { + Role = role; + Content = content; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MessageDelta() + { + } + + /// The entity that produced the message. + public MessageRole Role { get; } + /// + /// The content of the message as an array of text and/or images. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public IReadOnlyList Content { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.Serialization.cs similarity index 61% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.Serialization.cs index c1c5a4d65a5f..0021de85df1f 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.Serialization.cs @@ -13,27 +13,25 @@ namespace Azure.AI.OpenAI.Assistants { - public partial class MessageFile : IUtf8JsonSerializable, IJsonModel + public partial class MessageDeltaChunk : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(MessageFile)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(MessageDeltaChunk)} does not support writing '{format}' format."); } writer.WriteStartObject(); writer.WritePropertyName("id"u8); writer.WriteStringValue(Id); writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object); - writer.WritePropertyName("created_at"u8); - writer.WriteNumberValue(CreatedAt, "U"); - writer.WritePropertyName("message_id"u8); - writer.WriteStringValue(MessageId); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("delta"u8); + writer.WriteObjectValue(Delta, options); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -52,19 +50,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio writer.WriteEndObject(); } - MessageFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + MessageDeltaChunk 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(MessageFile)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(MessageDeltaChunk)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeMessageFile(document.RootElement, options); + return DeserializeMessageDeltaChunk(document.RootElement, options); } - internal static MessageFile DeserializeMessageFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static MessageDeltaChunk DeserializeMessageDeltaChunk(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -73,9 +71,8 @@ internal static MessageFile DeserializeMessageFile(JsonElement element, ModelRea return null; } string id = default; - string @object = default; - DateTimeOffset createdAt = default; - string messageId = default; + MessageDeltaChunkObject @object = default; + MessageDelta delta = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -87,17 +84,12 @@ internal static MessageFile DeserializeMessageFile(JsonElement element, ModelRea } if (property.NameEquals("object"u8)) { - @object = property.Value.GetString(); + @object = new MessageDeltaChunkObject(property.Value.GetString()); continue; } - if (property.NameEquals("created_at"u8)) + if (property.NameEquals("delta"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); - continue; - } - if (property.NameEquals("message_id"u8)) - { - messageId = property.Value.GetString(); + delta = MessageDelta.DeserializeMessageDelta(property.Value, options); continue; } if (options.Format != "W") @@ -106,46 +98,46 @@ internal static MessageFile DeserializeMessageFile(JsonElement element, ModelRea } } serializedAdditionalRawData = rawDataDictionary; - return new MessageFile(id, @object, createdAt, messageId, serializedAdditionalRawData); + return new MessageDeltaChunk(id, @object, delta, 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(MessageFile)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(MessageDeltaChunk)} does not support writing '{options.Format}' format."); } } - MessageFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + MessageDeltaChunk 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 DeserializeMessageFile(document.RootElement, options); + return DeserializeMessageDeltaChunk(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(MessageFile)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(MessageDeltaChunk)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static MessageFile FromResponse(Response response) + internal static MessageDeltaChunk FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeMessageFile(document.RootElement); + return DeserializeMessageDeltaChunk(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.cs similarity index 56% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.cs index a33691868926..3a8984a1a101 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.cs @@ -10,8 +10,8 @@ namespace Azure.AI.OpenAI.Assistants { - /// Information about a file attached to an assistant thread message. - public partial class MessageFile + /// Represents a message delta i.e. any changed fields on a message during streaming. + public partial class MessageDeltaChunk { /// /// Keeps track of any properties unknown to the library. @@ -45,47 +45,43 @@ public partial class MessageFile /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - /// The identifier, which can be referenced in API endpoints. - /// The Unix timestamp, in seconds, representing when this object was created. - /// The ID of the message that this file is attached to. - /// or is null. - internal MessageFile(string id, DateTimeOffset createdAt, string messageId) + /// Initializes a new instance of . + /// The identifier of the message, which can be referenced in API endpoints. + /// The delta containing the fields that have changed on the Message. + /// or is null. + internal MessageDeltaChunk(string id, MessageDelta delta) { Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(messageId, nameof(messageId)); + Argument.AssertNotNull(delta, nameof(delta)); Id = id; - CreatedAt = createdAt; - MessageId = messageId; + Delta = delta; } - /// Initializes a new instance of . - /// The identifier, which can be referenced in API endpoints. - /// The object type, which is always 'thread.message.file'. - /// The Unix timestamp, in seconds, representing when this object was created. - /// The ID of the message that this file is attached to. + /// Initializes a new instance of . + /// The identifier of the message, which can be referenced in API endpoints. + /// The object type, which is always `thread.message.delta`. + /// The delta containing the fields that have changed on the Message. /// Keeps track of any properties unknown to the library. - internal MessageFile(string id, string @object, DateTimeOffset createdAt, string messageId, IDictionary serializedAdditionalRawData) + internal MessageDeltaChunk(string id, MessageDeltaChunkObject @object, MessageDelta delta, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; - CreatedAt = createdAt; - MessageId = messageId; + Delta = delta; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal MessageFile() + /// Initializes a new instance of for deserialization. + internal MessageDeltaChunk() { } - /// The identifier, which can be referenced in API endpoints. + /// The identifier of the message, which can be referenced in API endpoints. public string Id { get; } + /// The object type, which is always `thread.message.delta`. + public MessageDeltaChunkObject Object { get; } = MessageDeltaChunkObject.ThreadMessageDelta; - /// The Unix timestamp, in seconds, representing when this object was created. - public DateTimeOffset CreatedAt { get; } - /// The ID of the message that this file is attached to. - public string MessageId { get; } + /// The delta containing the fields that have changed on the Message. + public MessageDelta Delta { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunkObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunkObject.cs new file mode 100644 index 000000000000..b8b58471b5b6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunkObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The MessageDeltaChunk_object. + public readonly partial struct MessageDeltaChunkObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public MessageDeltaChunkObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadMessageDeltaValue = "thread.message.delta"; + + /// thread.message.delta. + public static MessageDeltaChunkObject ThreadMessageDelta { get; } = new MessageDeltaChunkObject(ThreadMessageDeltaValue); + /// Determines if two values are the same. + public static bool operator ==(MessageDeltaChunkObject left, MessageDeltaChunkObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(MessageDeltaChunkObject left, MessageDeltaChunkObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator MessageDeltaChunkObject(string value) => new MessageDeltaChunkObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MessageDeltaChunkObject other && Equals(other); + /// + public bool Equals(MessageDeltaChunkObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.Serialization.cs new file mode 100644 index 000000000000..772c6f38dba4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.Serialization.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownMessageDeltaContent))] + public partial class MessageDeltaContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaContent)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaContent 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(MessageDeltaContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaContent(document.RootElement, options); + } + + internal static MessageDeltaContent DeserializeMessageDeltaContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "image_file": return MessageDeltaImageFileContent.DeserializeMessageDeltaImageFileContent(element, options); + case "text": return MessageDeltaTextContentObject.DeserializeMessageDeltaTextContentObject(element, options); + } + } + return UnknownMessageDeltaContent.DeserializeUnknownMessageDeltaContent(element, 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(MessageDeltaContent)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaContent 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 DeserializeMessageDeltaContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeltaContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.cs new file mode 100644 index 000000000000..454d8e437f56 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// The abstract base representation of a partial streamed message content payload. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class MessageDeltaContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The index of the content part of the message. + protected MessageDeltaContent(int index) + { + Index = index; + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The type of content for this content part. + /// Keeps track of any properties unknown to the library. + internal MessageDeltaContent(int index, string type, IDictionary serializedAdditionalRawData) + { + Index = index; + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaContent() + { + } + + /// The index of the content part of the message. + public int Index { get; } + /// The type of content for this content part. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.Serialization.cs new file mode 100644 index 000000000000..b5fb1b24e1d1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaImageFileContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaImageFileContent)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(ImageFile)) + { + writer.WritePropertyName("image_file"u8); + writer.WriteObjectValue(ImageFile, options); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaImageFileContent 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(MessageDeltaImageFileContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaImageFileContent(document.RootElement, options); + } + + internal static MessageDeltaImageFileContent DeserializeMessageDeltaImageFileContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageDeltaImageFileContentObject imageFile = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("image_file"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + imageFile = MessageDeltaImageFileContentObject.DeserializeMessageDeltaImageFileContentObject(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaImageFileContent(index, type, serializedAdditionalRawData, imageFile); + } + + 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(MessageDeltaImageFileContent)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaImageFileContent 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 DeserializeMessageDeltaImageFileContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaImageFileContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new MessageDeltaImageFileContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeltaImageFileContent(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.cs new file mode 100644 index 000000000000..212421c7c2e7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a streamed image file content part within a streaming message delta chunk. + public partial class MessageDeltaImageFileContent : MessageDeltaContent + { + /// Initializes a new instance of . + /// The index of the content part of the message. + internal MessageDeltaImageFileContent(int index) : base(index) + { + Type = "image_file"; + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The type of content for this content part. + /// Keeps track of any properties unknown to the library. + /// The image_file data. + internal MessageDeltaImageFileContent(int index, string type, IDictionary serializedAdditionalRawData, MessageDeltaImageFileContentObject imageFile) : base(index, type, serializedAdditionalRawData) + { + ImageFile = imageFile; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaImageFileContent() + { + } + + /// The image_file data. + public MessageDeltaImageFileContentObject ImageFile { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.Serialization.cs new file mode 100644 index 000000000000..058851b1fc5e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.Serialization.cs @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaImageFileContentObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaImageFileContentObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(FileId)) + { + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaImageFileContentObject 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(MessageDeltaImageFileContentObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaImageFileContentObject(document.RootElement, options); + } + + internal static MessageDeltaImageFileContentObject DeserializeMessageDeltaImageFileContentObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaImageFileContentObject(fileId, serializedAdditionalRawData); + } + + 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(MessageDeltaImageFileContentObject)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaImageFileContentObject 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 DeserializeMessageDeltaImageFileContentObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaImageFileContentObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaImageFileContentObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeltaImageFileContentObject(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.cs new file mode 100644 index 000000000000..592b0e9cef60 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the 'image_file' payload within streaming image file content. + public partial class MessageDeltaImageFileContentObject + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal MessageDeltaImageFileContentObject() + { + } + + /// Initializes a new instance of . + /// The file ID of the image in the message content. + /// Keeps track of any properties unknown to the library. + internal MessageDeltaImageFileContentObject(string fileId, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The file ID of the image in the message content. + public string FileId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.Serialization.cs new file mode 100644 index 000000000000..d8cce0302222 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.Serialization.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownMessageDeltaTextAnnotation))] + public partial class MessageDeltaTextAnnotation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaTextAnnotation)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaTextAnnotation 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(MessageDeltaTextAnnotation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextAnnotation(document.RootElement, options); + } + + internal static MessageDeltaTextAnnotation DeserializeMessageDeltaTextAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "file_citation": return MessageDeltaTextFileCitationAnnotationObject.DeserializeMessageDeltaTextFileCitationAnnotationObject(element, options); + case "file_path": return MessageDeltaTextFilePathAnnotationObject.DeserializeMessageDeltaTextFilePathAnnotationObject(element, options); + } + } + return UnknownMessageDeltaTextAnnotation.DeserializeUnknownMessageDeltaTextAnnotation(element, 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(MessageDeltaTextAnnotation)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextAnnotation 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 DeserializeMessageDeltaTextAnnotation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextAnnotation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaTextAnnotation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeltaTextAnnotation(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.cs new file mode 100644 index 000000000000..2171bf6148cb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// The abstract base representation of a streamed text content part's text annotation. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class MessageDeltaTextAnnotation + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + protected MessageDeltaTextAnnotation(int index) + { + Index = index; + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The type of the text content annotation. + /// Keeps track of any properties unknown to the library. + internal MessageDeltaTextAnnotation(int index, string type, IDictionary serializedAdditionalRawData) + { + Index = index; + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaTextAnnotation() + { + } + + /// The index of the annotation within a text content part. + public int Index { get; } + /// The type of the text content annotation. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.Serialization.cs new file mode 100644 index 000000000000..49e3cab4ca65 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.Serialization.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaTextContent)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Value)) + { + writer.WritePropertyName("value"u8); + writer.WriteStringValue(Value); + } + if (Optional.IsCollectionDefined(Annotations)) + { + writer.WritePropertyName("annotations"u8); + writer.WriteStartArray(); + foreach (var item in Annotations) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaTextContent 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(MessageDeltaTextContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextContent(document.RootElement, options); + } + + internal static MessageDeltaTextContent DeserializeMessageDeltaTextContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string value = default; + IReadOnlyList annotations = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + value = property.Value.GetString(); + continue; + } + if (property.NameEquals("annotations"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(MessageDeltaTextAnnotation.DeserializeMessageDeltaTextAnnotation(item, options)); + } + annotations = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextContent(value, annotations ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + 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(MessageDeltaTextContent)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextContent 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 DeserializeMessageDeltaTextContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaTextContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeltaTextContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.cs new file mode 100644 index 000000000000..15c4cac2d7ca --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the data of a streamed text content part within a streaming message delta chunk. + public partial class MessageDeltaTextContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal MessageDeltaTextContent() + { + Annotations = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The data that makes up the text. + /// + /// Annotations for the text. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal MessageDeltaTextContent(string value, IReadOnlyList annotations, IDictionary serializedAdditionalRawData) + { + Value = value; + Annotations = annotations; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The data that makes up the text. + public string Value { get; } + /// + /// Annotations for the text. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public IReadOnlyList Annotations { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.Serialization.cs new file mode 100644 index 000000000000..7261ccd92cb4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextContentObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaTextContentObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Text)) + { + writer.WritePropertyName("text"u8); + writer.WriteObjectValue(Text, options); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaTextContentObject 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(MessageDeltaTextContentObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextContentObject(document.RootElement, options); + } + + internal static MessageDeltaTextContentObject DeserializeMessageDeltaTextContentObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageDeltaTextContent text = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + text = MessageDeltaTextContent.DeserializeMessageDeltaTextContent(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextContentObject(index, type, serializedAdditionalRawData, text); + } + + 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(MessageDeltaTextContentObject)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextContentObject 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 DeserializeMessageDeltaTextContentObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextContentObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new MessageDeltaTextContentObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeltaTextContentObject(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.cs new file mode 100644 index 000000000000..54247431988a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a streamed text content part within a streaming message delta chunk. + public partial class MessageDeltaTextContentObject : MessageDeltaContent + { + /// Initializes a new instance of . + /// The index of the content part of the message. + internal MessageDeltaTextContentObject(int index) : base(index) + { + Type = "text"; + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The type of content for this content part. + /// Keeps track of any properties unknown to the library. + /// The text content details. + internal MessageDeltaTextContentObject(int index, string type, IDictionary serializedAdditionalRawData, MessageDeltaTextContent text) : base(index, type, serializedAdditionalRawData) + { + Text = text; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaTextContentObject() + { + } + + /// The text content details. + public MessageDeltaTextContent Text { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.Serialization.cs new file mode 100644 index 000000000000..155551a551c7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.Serialization.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextFileCitationAnnotation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaTextFileCitationAnnotation)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(FileId)) + { + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + } + if (Optional.IsDefined(Quote)) + { + writer.WritePropertyName("quote"u8); + writer.WriteStringValue(Quote); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaTextFileCitationAnnotation 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(MessageDeltaTextFileCitationAnnotation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextFileCitationAnnotation(document.RootElement, options); + } + + internal static MessageDeltaTextFileCitationAnnotation DeserializeMessageDeltaTextFileCitationAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + string quote = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("quote"u8)) + { + quote = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextFileCitationAnnotation(fileId, quote, serializedAdditionalRawData); + } + + 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(MessageDeltaTextFileCitationAnnotation)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextFileCitationAnnotation 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 DeserializeMessageDeltaTextFileCitationAnnotation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFileCitationAnnotation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaTextFileCitationAnnotation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeltaTextFileCitationAnnotation(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.cs new file mode 100644 index 000000000000..6f2fd703c231 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the data of a streamed file citation as applied to a streaming text content part. + public partial class MessageDeltaTextFileCitationAnnotation + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal MessageDeltaTextFileCitationAnnotation() + { + } + + /// Initializes a new instance of . + /// The ID of the specific file the citation is from. + /// The specific quote in the cited file. + /// Keeps track of any properties unknown to the library. + internal MessageDeltaTextFileCitationAnnotation(string fileId, string quote, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + Quote = quote; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The ID of the specific file the citation is from. + public string FileId { get; } + /// The specific quote in the cited file. + public string Quote { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.Serialization.cs new file mode 100644 index 000000000000..9fde82d67e2e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.Serialization.cs @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextFileCitationAnnotationObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaTextFileCitationAnnotationObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(FileCitation)) + { + writer.WritePropertyName("file_citation"u8); + writer.WriteObjectValue(FileCitation, options); + } + if (Optional.IsDefined(Text)) + { + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + } + if (Optional.IsDefined(StartIndex)) + { + writer.WritePropertyName("start_index"u8); + writer.WriteNumberValue(StartIndex.Value); + } + if (Optional.IsDefined(EndIndex)) + { + writer.WritePropertyName("end_index"u8); + writer.WriteNumberValue(EndIndex.Value); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaTextFileCitationAnnotationObject 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(MessageDeltaTextFileCitationAnnotationObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextFileCitationAnnotationObject(document.RootElement, options); + } + + internal static MessageDeltaTextFileCitationAnnotationObject DeserializeMessageDeltaTextFileCitationAnnotationObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageDeltaTextFileCitationAnnotation fileCitation = default; + string text = default; + int? startIndex = default; + int? endIndex = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_citation"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileCitation = MessageDeltaTextFileCitationAnnotation.DeserializeMessageDeltaTextFileCitationAnnotation(property.Value, options); + continue; + } + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("start_index"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + startIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("end_index"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextFileCitationAnnotationObject( + index, + type, + serializedAdditionalRawData, + fileCitation, + text, + startIndex, + endIndex); + } + + 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(MessageDeltaTextFileCitationAnnotationObject)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextFileCitationAnnotationObject 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 DeserializeMessageDeltaTextFileCitationAnnotationObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFileCitationAnnotationObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new MessageDeltaTextFileCitationAnnotationObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeltaTextFileCitationAnnotationObject(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.cs new file mode 100644 index 000000000000..1a67dafe8dfa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.cs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a streamed file citation applied to a streaming text content part. + public partial class MessageDeltaTextFileCitationAnnotationObject : MessageDeltaTextAnnotation + { + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + internal MessageDeltaTextFileCitationAnnotationObject(int index) : base(index) + { + Type = "file_citation"; + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The type of the text content annotation. + /// Keeps track of any properties unknown to the library. + /// The file citation information. + /// The text in the message content that needs to be replaced. + /// The start index of this annotation in the content text. + /// The end index of this annotation in the content text. + internal MessageDeltaTextFileCitationAnnotationObject(int index, string type, IDictionary serializedAdditionalRawData, MessageDeltaTextFileCitationAnnotation fileCitation, string text, int? startIndex, int? endIndex) : base(index, type, serializedAdditionalRawData) + { + FileCitation = fileCitation; + Text = text; + StartIndex = startIndex; + EndIndex = endIndex; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaTextFileCitationAnnotationObject() + { + } + + /// The file citation information. + public MessageDeltaTextFileCitationAnnotation FileCitation { get; } + /// The text in the message content that needs to be replaced. + public string Text { get; } + /// The start index of this annotation in the content text. + public int? StartIndex { get; } + /// The end index of this annotation in the content text. + public int? EndIndex { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.Serialization.cs new file mode 100644 index 000000000000..dcbbf8904dde --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.Serialization.cs @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextFilePathAnnotation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaTextFilePathAnnotation)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(FileId)) + { + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaTextFilePathAnnotation 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(MessageDeltaTextFilePathAnnotation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextFilePathAnnotation(document.RootElement, options); + } + + internal static MessageDeltaTextFilePathAnnotation DeserializeMessageDeltaTextFilePathAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextFilePathAnnotation(fileId, serializedAdditionalRawData); + } + + 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(MessageDeltaTextFilePathAnnotation)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextFilePathAnnotation 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 DeserializeMessageDeltaTextFilePathAnnotation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFilePathAnnotation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaTextFilePathAnnotation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeltaTextFilePathAnnotation(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.cs new file mode 100644 index 000000000000..dbdd8626dc56 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the data of a streamed file path annotation as applied to a streaming text content part. + public partial class MessageDeltaTextFilePathAnnotation + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal MessageDeltaTextFilePathAnnotation() + { + } + + /// Initializes a new instance of . + /// The file ID for the annotation. + /// Keeps track of any properties unknown to the library. + internal MessageDeltaTextFilePathAnnotation(string fileId, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The file ID for the annotation. + public string FileId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.Serialization.cs new file mode 100644 index 000000000000..2acabd3d49c5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.Serialization.cs @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextFilePathAnnotationObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaTextFilePathAnnotationObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(FilePath)) + { + writer.WritePropertyName("file_path"u8); + writer.WriteObjectValue(FilePath, options); + } + if (Optional.IsDefined(StartIndex)) + { + writer.WritePropertyName("start_index"u8); + writer.WriteNumberValue(StartIndex.Value); + } + if (Optional.IsDefined(EndIndex)) + { + writer.WritePropertyName("end_index"u8); + writer.WriteNumberValue(EndIndex.Value); + } + if (Optional.IsDefined(Text)) + { + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaTextFilePathAnnotationObject 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(MessageDeltaTextFilePathAnnotationObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextFilePathAnnotationObject(document.RootElement, options); + } + + internal static MessageDeltaTextFilePathAnnotationObject DeserializeMessageDeltaTextFilePathAnnotationObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageDeltaTextFilePathAnnotation filePath = default; + int? startIndex = default; + int? endIndex = default; + string text = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_path"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + filePath = MessageDeltaTextFilePathAnnotation.DeserializeMessageDeltaTextFilePathAnnotation(property.Value, options); + continue; + } + if (property.NameEquals("start_index"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + startIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("end_index"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextFilePathAnnotationObject( + index, + type, + serializedAdditionalRawData, + filePath, + startIndex, + endIndex, + text); + } + + 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(MessageDeltaTextFilePathAnnotationObject)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextFilePathAnnotationObject 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 DeserializeMessageDeltaTextFilePathAnnotationObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFilePathAnnotationObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new MessageDeltaTextFilePathAnnotationObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageDeltaTextFilePathAnnotationObject(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.cs new file mode 100644 index 000000000000..85df4f20c57d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.cs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a streamed file path annotation applied to a streaming text content part. + public partial class MessageDeltaTextFilePathAnnotationObject : MessageDeltaTextAnnotation + { + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + internal MessageDeltaTextFilePathAnnotationObject(int index) : base(index) + { + Type = "file_path"; + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The type of the text content annotation. + /// Keeps track of any properties unknown to the library. + /// The file path information. + /// The start index of this annotation in the content text. + /// The end index of this annotation in the content text. + /// The text in the message content that needs to be replaced. + internal MessageDeltaTextFilePathAnnotationObject(int index, string type, IDictionary serializedAdditionalRawData, MessageDeltaTextFilePathAnnotation filePath, int? startIndex, int? endIndex, string text) : base(index, type, serializedAdditionalRawData) + { + FilePath = filePath; + StartIndex = startIndex; + EndIndex = endIndex; + Text = text; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaTextFilePathAnnotationObject() + { + } + + /// The file path information. + public MessageDeltaTextFilePathAnnotation FilePath { get; } + /// The start index of this annotation in the content text. + public int? StartIndex { get; } + /// The end index of this annotation in the content text. + public int? EndIndex { get; } + /// The text in the message content that needs to be replaced. + public string Text { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageImageFileContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageImageFileContent.cs index 8997ff05b177..7e252658ea5e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageImageFileContent.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageImageFileContent.cs @@ -16,7 +16,7 @@ public partial class MessageImageFileContent : MessageContent /// Initializes a new instance of . /// The image file for this thread message content item. /// is null. - internal MessageImageFileContent(InternalMessageImageFileDetails internalDetails) + public MessageImageFileContent(InternalMessageImageFileDetails internalDetails) { Argument.AssertNotNull(internalDetails, nameof(internalDetails)); diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.Serialization.cs new file mode 100644 index 000000000000..bee6aeb930a2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageIncompleteDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageIncompleteDetails)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("reason"u8); + writer.WriteStringValue(Reason.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageIncompleteDetails 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(MessageIncompleteDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageIncompleteDetails(document.RootElement, options); + } + + internal static MessageIncompleteDetails DeserializeMessageIncompleteDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageIncompleteDetailsReason reason = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("reason"u8)) + { + reason = new MessageIncompleteDetailsReason(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageIncompleteDetails(reason, serializedAdditionalRawData); + } + + 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(MessageIncompleteDetails)} does not support writing '{options.Format}' format."); + } + } + + MessageIncompleteDetails 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 DeserializeMessageIncompleteDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageIncompleteDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageIncompleteDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMessageIncompleteDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.cs new file mode 100644 index 000000000000..335c1009db7f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Information providing additional detail about a message entering an incomplete status. + public partial class MessageIncompleteDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The provided reason describing why the message was marked as incomplete. + public MessageIncompleteDetails(MessageIncompleteDetailsReason reason) + { + Reason = reason; + } + + /// Initializes a new instance of . + /// The provided reason describing why the message was marked as incomplete. + /// Keeps track of any properties unknown to the library. + internal MessageIncompleteDetails(MessageIncompleteDetailsReason reason, IDictionary serializedAdditionalRawData) + { + Reason = reason; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MessageIncompleteDetails() + { + } + + /// The provided reason describing why the message was marked as incomplete. + public MessageIncompleteDetailsReason Reason { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetailsReason.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetailsReason.cs new file mode 100644 index 000000000000..ec0c57835d91 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetailsReason.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A set of reasons describing why a message is marked as incomplete. + public readonly partial struct MessageIncompleteDetailsReason : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public MessageIncompleteDetailsReason(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ContentFilterValue = "content_filter"; + private const string MaxTokensValue = "max_tokens"; + private const string RunCancelledValue = "run_cancelled"; + private const string RunFailedValue = "run_failed"; + private const string RunExpiredValue = "run_expired"; + + /// The run generating the message was terminated due to content filter flagging. + public static MessageIncompleteDetailsReason ContentFilter { get; } = new MessageIncompleteDetailsReason(ContentFilterValue); + /// The run generating the message exhausted available tokens before completion. + public static MessageIncompleteDetailsReason MaxTokens { get; } = new MessageIncompleteDetailsReason(MaxTokensValue); + /// The run generating the message was cancelled before completion. + public static MessageIncompleteDetailsReason RunCancelled { get; } = new MessageIncompleteDetailsReason(RunCancelledValue); + /// The run generating the message failed. + public static MessageIncompleteDetailsReason RunFailed { get; } = new MessageIncompleteDetailsReason(RunFailedValue); + /// The run generating the message expired. + public static MessageIncompleteDetailsReason RunExpired { get; } = new MessageIncompleteDetailsReason(RunExpiredValue); + /// Determines if two values are the same. + public static bool operator ==(MessageIncompleteDetailsReason left, MessageIncompleteDetailsReason right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(MessageIncompleteDetailsReason left, MessageIncompleteDetailsReason right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator MessageIncompleteDetailsReason(string value) => new MessageIncompleteDetailsReason(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MessageIncompleteDetailsReason other && Equals(other); + /// + public bool Equals(MessageIncompleteDetailsReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStatus.cs new file mode 100644 index 000000000000..d63a6bcf8b56 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStatus.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The possible execution status values for a thread message. + public readonly partial struct MessageStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public MessageStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InProgressValue = "in_progress"; + private const string IncompleteValue = "incomplete"; + private const string CompletedValue = "completed"; + + /// A run is currently creating this message. + public static MessageStatus InProgress { get; } = new MessageStatus(InProgressValue); + /// This message is incomplete. See incomplete_details for more information. + public static MessageStatus Incomplete { get; } = new MessageStatus(IncompleteValue); + /// This message was successfully completed by a run. + public static MessageStatus Completed { get; } = new MessageStatus(CompletedValue); + /// Determines if two values are the same. + public static bool operator ==(MessageStatus left, MessageStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(MessageStatus left, MessageStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator MessageStatus(string value) => new MessageStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MessageStatus other && Equals(other); + /// + public bool Equals(MessageStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStreamEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStreamEvent.cs new file mode 100644 index 000000000000..13c90b7d0b77 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStreamEvent.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Message operation related streaming events. + public readonly partial struct MessageStreamEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public MessageStreamEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadMessageCreatedValue = "thread.message.created"; + private const string ThreadMessageInProgressValue = "thread.message.in_progress"; + private const string ThreadMessageDeltaValue = "thread.message.delta"; + private const string ThreadMessageCompletedValue = "thread.message.completed"; + private const string ThreadMessageIncompleteValue = "thread.message.incomplete"; + + /// Event sent when a new message is created. The data of this event is of type ThreadMessage. + public static MessageStreamEvent ThreadMessageCreated { get; } = new MessageStreamEvent(ThreadMessageCreatedValue); + /// Event sent when a message moves to `in_progress` status. The data of this event is of type ThreadMessage. + public static MessageStreamEvent ThreadMessageInProgress { get; } = new MessageStreamEvent(ThreadMessageInProgressValue); + /// Event sent when a message is being streamed. The data of this event is of type MessageDeltaChunk. + public static MessageStreamEvent ThreadMessageDelta { get; } = new MessageStreamEvent(ThreadMessageDeltaValue); + /// Event sent when a message is completed. The data of this event is of type ThreadMessage. + public static MessageStreamEvent ThreadMessageCompleted { get; } = new MessageStreamEvent(ThreadMessageCompletedValue); + /// Event sent before a message is completed. The data of this event is of type ThreadMessage. + public static MessageStreamEvent ThreadMessageIncomplete { get; } = new MessageStreamEvent(ThreadMessageIncompleteValue); + /// Determines if two values are the same. + public static bool operator ==(MessageStreamEvent left, MessageStreamEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(MessageStreamEvent left, MessageStreamEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator MessageStreamEvent(string value) => new MessageStreamEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MessageStreamEvent other && Equals(other); + /// + public bool Equals(MessageStreamEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.Serialization.cs index ae962644a772..99920983550d 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.Serialization.cs @@ -30,10 +30,6 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW writer.WriteStringValue(Type); writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); - writer.WritePropertyName("start_index"u8); - writer.WriteNumberValue(StartIndex); - writer.WritePropertyName("end_index"u8); - writer.WriteNumberValue(EndIndex); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.cs index 082f8fea6a5b..aa8769d7ed21 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.cs @@ -51,30 +51,22 @@ public abstract partial class MessageTextAnnotation /// Initializes a new instance of . /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// is null. - protected MessageTextAnnotation(string text, int startIndex, int endIndex) + protected MessageTextAnnotation(string text) { Argument.AssertNotNull(text, nameof(text)); Text = text; - StartIndex = startIndex; - EndIndex = endIndex; } /// Initializes a new instance of . /// The object type. /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// Keeps track of any properties unknown to the library. - internal MessageTextAnnotation(string type, string text, int startIndex, int endIndex, IDictionary serializedAdditionalRawData) + internal MessageTextAnnotation(string type, string text, IDictionary serializedAdditionalRawData) { Type = type; Text = text; - StartIndex = startIndex; - EndIndex = endIndex; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -86,10 +78,6 @@ internal MessageTextAnnotation() /// The object type. internal string Type { get; set; } /// The textual content associated with this text annotation item. - public string Text { get; } - /// The first text index associated with this text annotation. - public int StartIndex { get; } - /// The last text index associated with this text annotation. - public int EndIndex { get; } + public string Text { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextContent.cs index 61d7241bb927..ef579043014c 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextContent.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextContent.cs @@ -16,7 +16,7 @@ public partial class MessageTextContent : MessageContent /// Initializes a new instance of . /// The text and associated annotations for this thread message content item. /// is null. - internal MessageTextContent(InternalMessageTextDetails internalDetails) + public MessageTextContent(InternalMessageTextDetails internalDetails) { Argument.AssertNotNull(internalDetails, nameof(internalDetails)); diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.Serialization.cs index 986e6b38dfe0..858b184a6495 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.Serialization.cs @@ -28,14 +28,20 @@ void IJsonModel.Write(Utf8JsonWriter writer, writer.WriteStartObject(); writer.WritePropertyName("file_citation"u8); writer.WriteObjectValue(InternalDetails, options); + if (Optional.IsDefined(StartIndex)) + { + writer.WritePropertyName("start_index"u8); + writer.WriteNumberValue(StartIndex.Value); + } + if (Optional.IsDefined(EndIndex)) + { + writer.WritePropertyName("end_index"u8); + writer.WriteNumberValue(EndIndex.Value); + } writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); - writer.WritePropertyName("start_index"u8); - writer.WriteNumberValue(StartIndex); - writer.WritePropertyName("end_index"u8); - writer.WriteNumberValue(EndIndex); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -75,10 +81,10 @@ internal static MessageTextFileCitationAnnotation DeserializeMessageTextFileCita return null; } InternalMessageTextFileCitationDetails fileCitation = default; + int? startIndex = default; + int? endIndex = default; string type = default; string text = default; - int startIndex = default; - int endIndex = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -88,24 +94,32 @@ internal static MessageTextFileCitationAnnotation DeserializeMessageTextFileCita fileCitation = InternalMessageTextFileCitationDetails.DeserializeInternalMessageTextFileCitationDetails(property.Value, options); continue; } - if (property.NameEquals("type"u8)) + if (property.NameEquals("start_index"u8)) { - type = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + startIndex = property.Value.GetInt32(); continue; } - if (property.NameEquals("text"u8)) + if (property.NameEquals("end_index"u8)) { - text = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endIndex = property.Value.GetInt32(); continue; } - if (property.NameEquals("start_index"u8)) + if (property.NameEquals("type"u8)) { - startIndex = property.Value.GetInt32(); + type = property.Value.GetString(); continue; } - if (property.NameEquals("end_index"u8)) + if (property.NameEquals("text"u8)) { - endIndex = property.Value.GetInt32(); + text = property.Value.GetString(); continue; } if (options.Format != "W") @@ -117,10 +131,10 @@ internal static MessageTextFileCitationAnnotation DeserializeMessageTextFileCita return new MessageTextFileCitationAnnotation( type, text, - startIndex, - endIndex, serializedAdditionalRawData, - fileCitation); + fileCitation, + startIndex, + endIndex); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.cs index a036ec9b468b..6db943f9c9a3 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.cs @@ -10,19 +10,17 @@ namespace Azure.AI.OpenAI.Assistants { - /// A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the 'retrieval' tool to search files. + /// A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the 'file_search' tool to search files. public partial class MessageTextFileCitationAnnotation : MessageTextAnnotation { /// Initializes a new instance of . /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// /// A citation within the message that points to a specific quote from a specific file. - /// Generated when the assistant uses the "retrieval" tool to search files. + /// Generated when the assistant uses the "file_search" tool to search files. /// /// or is null. - internal MessageTextFileCitationAnnotation(string text, int startIndex, int endIndex, InternalMessageTextFileCitationDetails internalDetails) : base(text, startIndex, endIndex) + public MessageTextFileCitationAnnotation(string text, InternalMessageTextFileCitationDetails internalDetails) : base(text) { Argument.AssertNotNull(text, nameof(text)); Argument.AssertNotNull(internalDetails, nameof(internalDetails)); @@ -34,21 +32,27 @@ internal MessageTextFileCitationAnnotation(string text, int startIndex, int endI /// Initializes a new instance of . /// The object type. /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// Keeps track of any properties unknown to the library. /// /// A citation within the message that points to a specific quote from a specific file. - /// Generated when the assistant uses the "retrieval" tool to search files. + /// Generated when the assistant uses the "file_search" tool to search files. /// - internal MessageTextFileCitationAnnotation(string type, string text, int startIndex, int endIndex, IDictionary serializedAdditionalRawData, InternalMessageTextFileCitationDetails internalDetails) : base(type, text, startIndex, endIndex, serializedAdditionalRawData) + /// The first text index associated with this text annotation. + /// The last text index associated with this text annotation. + internal MessageTextFileCitationAnnotation(string type, string text, IDictionary serializedAdditionalRawData, InternalMessageTextFileCitationDetails internalDetails, int? startIndex, int? endIndex) : base(type, text, serializedAdditionalRawData) { InternalDetails = internalDetails; + StartIndex = startIndex; + EndIndex = endIndex; } /// Initializes a new instance of for deserialization. internal MessageTextFileCitationAnnotation() { } + /// The first text index associated with this text annotation. + public int? StartIndex { get; set; } + /// The last text index associated with this text annotation. + public int? EndIndex { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.Serialization.cs index 72659f5a0ea3..1b3342e369e5 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.Serialization.cs @@ -28,14 +28,20 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mode writer.WriteStartObject(); writer.WritePropertyName("file_path"u8); writer.WriteObjectValue(InternalDetails, options); + if (Optional.IsDefined(StartIndex)) + { + writer.WritePropertyName("start_index"u8); + writer.WriteNumberValue(StartIndex.Value); + } + if (Optional.IsDefined(EndIndex)) + { + writer.WritePropertyName("end_index"u8); + writer.WriteNumberValue(EndIndex.Value); + } writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); - writer.WritePropertyName("start_index"u8); - writer.WriteNumberValue(StartIndex); - writer.WritePropertyName("end_index"u8); - writer.WriteNumberValue(EndIndex); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -75,10 +81,10 @@ internal static MessageTextFilePathAnnotation DeserializeMessageTextFilePathAnno return null; } InternalMessageTextFilePathDetails filePath = default; + int? startIndex = default; + int? endIndex = default; string type = default; string text = default; - int startIndex = default; - int endIndex = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -88,24 +94,32 @@ internal static MessageTextFilePathAnnotation DeserializeMessageTextFilePathAnno filePath = InternalMessageTextFilePathDetails.DeserializeInternalMessageTextFilePathDetails(property.Value, options); continue; } - if (property.NameEquals("type"u8)) + if (property.NameEquals("start_index"u8)) { - type = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + startIndex = property.Value.GetInt32(); continue; } - if (property.NameEquals("text"u8)) + if (property.NameEquals("end_index"u8)) { - text = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endIndex = property.Value.GetInt32(); continue; } - if (property.NameEquals("start_index"u8)) + if (property.NameEquals("type"u8)) { - startIndex = property.Value.GetInt32(); + type = property.Value.GetString(); continue; } - if (property.NameEquals("end_index"u8)) + if (property.NameEquals("text"u8)) { - endIndex = property.Value.GetInt32(); + text = property.Value.GetString(); continue; } if (options.Format != "W") @@ -117,10 +131,10 @@ internal static MessageTextFilePathAnnotation DeserializeMessageTextFilePathAnno return new MessageTextFilePathAnnotation( type, text, - startIndex, - endIndex, serializedAdditionalRawData, - filePath); + filePath, + startIndex, + endIndex); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.cs index 787c70831f54..276bb7ded43d 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.cs @@ -15,11 +15,9 @@ public partial class MessageTextFilePathAnnotation : MessageTextAnnotation { /// Initializes a new instance of . /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// A URL for the file that's generated when the assistant used the code_interpreter tool to generate a file. /// or is null. - internal MessageTextFilePathAnnotation(string text, int startIndex, int endIndex, InternalMessageTextFilePathDetails internalDetails) : base(text, startIndex, endIndex) + public MessageTextFilePathAnnotation(string text, InternalMessageTextFilePathDetails internalDetails) : base(text) { Argument.AssertNotNull(text, nameof(text)); Argument.AssertNotNull(internalDetails, nameof(internalDetails)); @@ -31,18 +29,24 @@ internal MessageTextFilePathAnnotation(string text, int startIndex, int endIndex /// Initializes a new instance of . /// The object type. /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// Keeps track of any properties unknown to the library. /// A URL for the file that's generated when the assistant used the code_interpreter tool to generate a file. - internal MessageTextFilePathAnnotation(string type, string text, int startIndex, int endIndex, IDictionary serializedAdditionalRawData, InternalMessageTextFilePathDetails internalDetails) : base(type, text, startIndex, endIndex, serializedAdditionalRawData) + /// The first text index associated with this text annotation. + /// The last text index associated with this text annotation. + internal MessageTextFilePathAnnotation(string type, string text, IDictionary serializedAdditionalRawData, InternalMessageTextFilePathDetails internalDetails, int? startIndex, int? endIndex) : base(type, text, serializedAdditionalRawData) { InternalDetails = internalDetails; + StartIndex = startIndex; + EndIndex = endIndex; } /// Initializes a new instance of for deserialization. internal MessageTextFilePathAnnotation() { } + /// The first text index associated with this text annotation. + public int? StartIndex { get; set; } + /// The last text index associated with this text annotation. + public int? EndIndex { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.Serialization.cs index e553361292ff..eabac96c3ba5 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.Serialization.cs @@ -38,6 +38,16 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOption writer.WriteNumberValue(CreatedAt, "U"); writer.WritePropertyName("purpose"u8); writer.WriteStringValue(Purpose.ToString()); + if (Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.Value.ToString()); + } + if (Optional.IsDefined(StatusDetails)) + { + writer.WritePropertyName("status_details"u8); + writer.WriteStringValue(StatusDetails); + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -82,6 +92,8 @@ internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReade string filename = default; DateTimeOffset createdAt = default; OpenAIFilePurpose purpose = default; + FileState? status = default; + string statusDetails = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -116,6 +128,20 @@ internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReade purpose = new OpenAIFilePurpose(property.Value.GetString()); continue; } + if (property.NameEquals("status"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new FileState(property.Value.GetString()); + continue; + } + if (property.NameEquals("status_details"u8)) + { + statusDetails = property.Value.GetString(); + continue; + } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); @@ -129,6 +155,8 @@ internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReade filename, createdAt, purpose, + status, + statusDetails, serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.cs index 318f90d4c5a5..29264237fe5a 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.cs @@ -71,8 +71,10 @@ internal OpenAIFile(string id, int size, string filename, DateTimeOffset created /// The name of the file. /// The Unix timestamp, in seconds, representing when this object was created. /// The intended purpose of a file. + /// The state of the file. This field is available in Azure OpenAI only. + /// The error message with details in case processing of this file failed. This field is available in Azure OpenAI only. /// Keeps track of any properties unknown to the library. - internal OpenAIFile(string @object, string id, int size, string filename, DateTimeOffset createdAt, OpenAIFilePurpose purpose, IDictionary serializedAdditionalRawData) + internal OpenAIFile(string @object, string id, int size, string filename, DateTimeOffset createdAt, OpenAIFilePurpose purpose, FileState? status, string statusDetails, IDictionary serializedAdditionalRawData) { Object = @object; Id = id; @@ -80,6 +82,8 @@ internal OpenAIFile(string @object, string id, int size, string filename, DateTi Filename = filename; CreatedAt = createdAt; Purpose = purpose; + Status = status; + StatusDetails = statusDetails; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -98,5 +102,9 @@ internal OpenAIFile() public DateTimeOffset CreatedAt { get; } /// The intended purpose of a file. public OpenAIFilePurpose Purpose { get; } + /// The state of the file. This field is available in Azure OpenAI only. + public FileState? Status { get; } + /// The error message with details in case processing of this file failed. This field is available in Azure OpenAI only. + public string StatusDetails { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFilePurpose.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFilePurpose.cs index 50d531cac562..e58119d1b591 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFilePurpose.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFilePurpose.cs @@ -26,6 +26,9 @@ public OpenAIFilePurpose(string value) private const string FineTuneResultsValue = "fine-tune-results"; private const string AssistantsValue = "assistants"; private const string AssistantsOutputValue = "assistants_output"; + private const string BatchValue = "batch"; + private const string BatchOutputValue = "batch_output"; + private const string VisionValue = "vision"; /// Indicates a file is used for fine tuning input. public static OpenAIFilePurpose FineTune { get; } = new OpenAIFilePurpose(FineTuneValue); @@ -35,6 +38,12 @@ public OpenAIFilePurpose(string value) public static OpenAIFilePurpose Assistants { get; } = new OpenAIFilePurpose(AssistantsValue); /// Indicates a file is used as output by assistants. public static OpenAIFilePurpose AssistantsOutput { get; } = new OpenAIFilePurpose(AssistantsOutputValue); + /// Indicates a file is used as input to . + public static OpenAIFilePurpose Batch { get; } = new OpenAIFilePurpose(BatchValue); + /// Indicates a file is used as output by a vector store batch operation. + public static OpenAIFilePurpose BatchOutput { get; } = new OpenAIFilePurpose(BatchOutputValue); + /// Indicates a file is used as input to a vision operation. + public static OpenAIFilePurpose Vision { get; } = new OpenAIFilePurpose(VisionValue); /// Determines if two values are the same. public static bool operator ==(OpenAIFilePurpose left, OpenAIFilePurpose right) => left.Equals(right); /// Determines if two values are not the same. diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfAssistantFileObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfAssistantFileObject.cs deleted file mode 100644 index 1a72c0020e88..000000000000 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfAssistantFileObject.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI.Assistants -{ - /// The OpenAIPageableListOfAssistantFile_object. - internal readonly partial struct OpenAIPageableListOfAssistantFileObject : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public OpenAIPageableListOfAssistantFileObject(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ListValue = "list"; - - /// list. - public static OpenAIPageableListOfAssistantFileObject List { get; } = new OpenAIPageableListOfAssistantFileObject(ListValue); - /// Determines if two values are the same. - public static bool operator ==(OpenAIPageableListOfAssistantFileObject left, OpenAIPageableListOfAssistantFileObject right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(OpenAIPageableListOfAssistantFileObject left, OpenAIPageableListOfAssistantFileObject right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator OpenAIPageableListOfAssistantFileObject(string value) => new OpenAIPageableListOfAssistantFileObject(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is OpenAIPageableListOfAssistantFileObject other && Equals(other); - /// - public bool Equals(OpenAIPageableListOfAssistantFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.Serialization.cs similarity index 64% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.Serialization.cs index 0fc4a1b175c0..1103b6e11633 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.Serialization.cs @@ -13,16 +13,16 @@ namespace Azure.AI.OpenAI.Assistants { - internal partial class InternalOpenAIPageableListOfMessageFile : IUtf8JsonSerializable, IJsonModel + public partial class OpenAIPageableListOfVectorStore : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(InternalOpenAIPageableListOfMessageFile)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStore)} does not support writing '{format}' format."); } writer.WriteStartObject(); @@ -59,19 +59,19 @@ void IJsonModel.Write(Utf8JsonWriter wr writer.WriteEndObject(); } - InternalOpenAIPageableListOfMessageFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIPageableListOfVectorStore 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(InternalOpenAIPageableListOfMessageFile)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStore)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalOpenAIPageableListOfMessageFile(document.RootElement, options); + return DeserializeOpenAIPageableListOfVectorStore(document.RootElement, options); } - internal static InternalOpenAIPageableListOfMessageFile DeserializeInternalOpenAIPageableListOfMessageFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIPageableListOfVectorStore DeserializeOpenAIPageableListOfVectorStore(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -79,8 +79,8 @@ internal static InternalOpenAIPageableListOfMessageFile DeserializeInternalOpenA { return null; } - OpenAIPageableListOfMessageFileObject @object = default; - IReadOnlyList data = default; + OpenAIPageableListOfVectorStoreObject @object = default; + IReadOnlyList data = default; string firstId = default; string lastId = default; bool hasMore = default; @@ -90,15 +90,15 @@ internal static InternalOpenAIPageableListOfMessageFile DeserializeInternalOpenA { if (property.NameEquals("object"u8)) { - @object = new OpenAIPageableListOfMessageFileObject(property.Value.GetString()); + @object = new OpenAIPageableListOfVectorStoreObject(property.Value.GetString()); continue; } if (property.NameEquals("data"u8)) { - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(MessageFile.DeserializeMessageFile(item, options)); + array.Add(VectorStore.DeserializeVectorStore(item, options)); } data = array; continue; @@ -124,7 +124,7 @@ internal static InternalOpenAIPageableListOfMessageFile DeserializeInternalOpenA } } serializedAdditionalRawData = rawDataDictionary; - return new InternalOpenAIPageableListOfMessageFile( + return new OpenAIPageableListOfVectorStore( @object, data, firstId, @@ -133,43 +133,43 @@ internal static InternalOpenAIPageableListOfMessageFile DeserializeInternalOpenA 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(InternalOpenAIPageableListOfMessageFile)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStore)} does not support writing '{options.Format}' format."); } } - InternalOpenAIPageableListOfMessageFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + OpenAIPageableListOfVectorStore 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 DeserializeInternalOpenAIPageableListOfMessageFile(document.RootElement, options); + return DeserializeOpenAIPageableListOfVectorStore(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalOpenAIPageableListOfMessageFile)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStore)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static InternalOpenAIPageableListOfMessageFile FromResponse(Response response) + internal static OpenAIPageableListOfVectorStore FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalOpenAIPageableListOfMessageFile(document.RootElement); + return DeserializeOpenAIPageableListOfVectorStore(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.cs similarity index 78% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.cs index 7b5f1581bf67..1cfa1fd0b07d 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.cs @@ -12,7 +12,7 @@ namespace Azure.AI.OpenAI.Assistants { /// The response data for a requested list of items. - internal partial class InternalOpenAIPageableListOfAssistantFile + public partial class OpenAIPageableListOfVectorStore { /// /// Keeps track of any properties unknown to the library. @@ -46,13 +46,13 @@ internal partial class InternalOpenAIPageableListOfAssistantFile /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The requested list of items. /// The first ID represented in this list. /// The last ID represented in this list. /// A value indicating whether there are additional values available not captured in this list. /// , or is null. - internal InternalOpenAIPageableListOfAssistantFile(IEnumerable data, string firstId, string lastId, bool hasMore) + internal OpenAIPageableListOfVectorStore(IEnumerable data, string firstId, string lastId, bool hasMore) { Argument.AssertNotNull(data, nameof(data)); Argument.AssertNotNull(firstId, nameof(firstId)); @@ -64,14 +64,14 @@ internal InternalOpenAIPageableListOfAssistantFile(IEnumerable da HasMore = hasMore; } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The object type, which is always list. /// The requested list of items. /// The first ID represented in this list. /// The last ID represented in this list. /// A value indicating whether there are additional values available not captured in this list. /// Keeps track of any properties unknown to the library. - internal InternalOpenAIPageableListOfAssistantFile(OpenAIPageableListOfAssistantFileObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal OpenAIPageableListOfVectorStore(OpenAIPageableListOfVectorStoreObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) { Object = @object; Data = data; @@ -81,16 +81,16 @@ internal InternalOpenAIPageableListOfAssistantFile(OpenAIPageableListOfAssistant _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal InternalOpenAIPageableListOfAssistantFile() + /// Initializes a new instance of for deserialization. + internal OpenAIPageableListOfVectorStore() { } /// The object type, which is always list. - public OpenAIPageableListOfAssistantFileObject Object { get; } = OpenAIPageableListOfAssistantFileObject.List; + public OpenAIPageableListOfVectorStoreObject Object { get; } = OpenAIPageableListOfVectorStoreObject.List; /// The requested list of items. - public IReadOnlyList Data { get; } + public IReadOnlyList Data { get; } /// The first ID represented in this list. public string FirstId { get; } /// The last ID represented in this list. diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.Serialization.cs similarity index 63% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.Serialization.cs index cd37f4181261..b388e3fa26fb 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.Serialization.cs @@ -13,16 +13,16 @@ namespace Azure.AI.OpenAI.Assistants { - internal partial class InternalOpenAIPageableListOfAssistantFile : IUtf8JsonSerializable, IJsonModel + public partial class OpenAIPageableListOfVectorStoreFile : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(InternalOpenAIPageableListOfAssistantFile)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStoreFile)} does not support writing '{format}' format."); } writer.WriteStartObject(); @@ -59,19 +59,19 @@ void IJsonModel.Write(Utf8JsonWriter writer.WriteEndObject(); } - InternalOpenAIPageableListOfAssistantFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIPageableListOfVectorStoreFile 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(InternalOpenAIPageableListOfAssistantFile)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStoreFile)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalOpenAIPageableListOfAssistantFile(document.RootElement, options); + return DeserializeOpenAIPageableListOfVectorStoreFile(document.RootElement, options); } - internal static InternalOpenAIPageableListOfAssistantFile DeserializeInternalOpenAIPageableListOfAssistantFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIPageableListOfVectorStoreFile DeserializeOpenAIPageableListOfVectorStoreFile(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -79,8 +79,8 @@ internal static InternalOpenAIPageableListOfAssistantFile DeserializeInternalOpe { return null; } - OpenAIPageableListOfAssistantFileObject @object = default; - IReadOnlyList data = default; + OpenAIPageableListOfVectorStoreFileObject @object = default; + IReadOnlyList data = default; string firstId = default; string lastId = default; bool hasMore = default; @@ -90,15 +90,15 @@ internal static InternalOpenAIPageableListOfAssistantFile DeserializeInternalOpe { if (property.NameEquals("object"u8)) { - @object = new OpenAIPageableListOfAssistantFileObject(property.Value.GetString()); + @object = new OpenAIPageableListOfVectorStoreFileObject(property.Value.GetString()); continue; } if (property.NameEquals("data"u8)) { - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(AssistantFile.DeserializeAssistantFile(item, options)); + array.Add(VectorStoreFile.DeserializeVectorStoreFile(item, options)); } data = array; continue; @@ -124,7 +124,7 @@ internal static InternalOpenAIPageableListOfAssistantFile DeserializeInternalOpe } } serializedAdditionalRawData = rawDataDictionary; - return new InternalOpenAIPageableListOfAssistantFile( + return new OpenAIPageableListOfVectorStoreFile( @object, data, firstId, @@ -133,43 +133,43 @@ internal static InternalOpenAIPageableListOfAssistantFile DeserializeInternalOpe 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(InternalOpenAIPageableListOfAssistantFile)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStoreFile)} does not support writing '{options.Format}' format."); } } - InternalOpenAIPageableListOfAssistantFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + OpenAIPageableListOfVectorStoreFile 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 DeserializeInternalOpenAIPageableListOfAssistantFile(document.RootElement, options); + return DeserializeOpenAIPageableListOfVectorStoreFile(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalOpenAIPageableListOfAssistantFile)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStoreFile)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static InternalOpenAIPageableListOfAssistantFile FromResponse(Response response) + internal static OpenAIPageableListOfVectorStoreFile FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalOpenAIPageableListOfAssistantFile(document.RootElement); + return DeserializeOpenAIPageableListOfVectorStoreFile(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.cs similarity index 78% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.cs index 591f029940a1..8f4e487d59ad 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.cs @@ -12,7 +12,7 @@ namespace Azure.AI.OpenAI.Assistants { /// The response data for a requested list of items. - internal partial class InternalOpenAIPageableListOfMessageFile + public partial class OpenAIPageableListOfVectorStoreFile { /// /// Keeps track of any properties unknown to the library. @@ -46,13 +46,13 @@ internal partial class InternalOpenAIPageableListOfMessageFile /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The requested list of items. /// The first ID represented in this list. /// The last ID represented in this list. /// A value indicating whether there are additional values available not captured in this list. /// , or is null. - internal InternalOpenAIPageableListOfMessageFile(IEnumerable data, string firstId, string lastId, bool hasMore) + internal OpenAIPageableListOfVectorStoreFile(IEnumerable data, string firstId, string lastId, bool hasMore) { Argument.AssertNotNull(data, nameof(data)); Argument.AssertNotNull(firstId, nameof(firstId)); @@ -64,14 +64,14 @@ internal InternalOpenAIPageableListOfMessageFile(IEnumerable data, HasMore = hasMore; } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The object type, which is always list. /// The requested list of items. /// The first ID represented in this list. /// The last ID represented in this list. /// A value indicating whether there are additional values available not captured in this list. /// Keeps track of any properties unknown to the library. - internal InternalOpenAIPageableListOfMessageFile(OpenAIPageableListOfMessageFileObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal OpenAIPageableListOfVectorStoreFile(OpenAIPageableListOfVectorStoreFileObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) { Object = @object; Data = data; @@ -81,16 +81,16 @@ internal InternalOpenAIPageableListOfMessageFile(OpenAIPageableListOfMessageFile _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal InternalOpenAIPageableListOfMessageFile() + /// Initializes a new instance of for deserialization. + internal OpenAIPageableListOfVectorStoreFile() { } /// The object type, which is always list. - public OpenAIPageableListOfMessageFileObject Object { get; } = OpenAIPageableListOfMessageFileObject.List; + public OpenAIPageableListOfVectorStoreFileObject Object { get; } = OpenAIPageableListOfVectorStoreFileObject.List; /// The requested list of items. - public IReadOnlyList Data { get; } + public IReadOnlyList Data { get; } /// The first ID represented in this list. public string FirstId { get; } /// The last ID represented in this list. diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFileObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFileObject.cs new file mode 100644 index 000000000000..1c678fe63a61 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFileObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The OpenAIPageableListOfVectorStoreFile_object. + public readonly partial struct OpenAIPageableListOfVectorStoreFileObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OpenAIPageableListOfVectorStoreFileObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ListValue = "list"; + + /// list. + public static OpenAIPageableListOfVectorStoreFileObject List { get; } = new OpenAIPageableListOfVectorStoreFileObject(ListValue); + /// Determines if two values are the same. + public static bool operator ==(OpenAIPageableListOfVectorStoreFileObject left, OpenAIPageableListOfVectorStoreFileObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OpenAIPageableListOfVectorStoreFileObject left, OpenAIPageableListOfVectorStoreFileObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OpenAIPageableListOfVectorStoreFileObject(string value) => new OpenAIPageableListOfVectorStoreFileObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OpenAIPageableListOfVectorStoreFileObject other && Equals(other); + /// + public bool Equals(OpenAIPageableListOfVectorStoreFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfMessageFileObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreObject.cs similarity index 55% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfMessageFileObject.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreObject.cs index 9993d3b6fdec..38b2253eef2e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfMessageFileObject.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreObject.cs @@ -10,14 +10,14 @@ namespace Azure.AI.OpenAI.Assistants { - /// The OpenAIPageableListOfMessageFile_object. - internal readonly partial struct OpenAIPageableListOfMessageFileObject : IEquatable + /// The OpenAIPageableListOfVectorStore_object. + public readonly partial struct OpenAIPageableListOfVectorStoreObject : IEquatable { private readonly string _value; - /// Initializes a new instance of . + /// Initializes a new instance of . /// is null. - public OpenAIPageableListOfMessageFileObject(string value) + public OpenAIPageableListOfVectorStoreObject(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } @@ -25,19 +25,19 @@ public OpenAIPageableListOfMessageFileObject(string value) private const string ListValue = "list"; /// list. - public static OpenAIPageableListOfMessageFileObject List { get; } = new OpenAIPageableListOfMessageFileObject(ListValue); - /// Determines if two values are the same. - public static bool operator ==(OpenAIPageableListOfMessageFileObject left, OpenAIPageableListOfMessageFileObject right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(OpenAIPageableListOfMessageFileObject left, OpenAIPageableListOfMessageFileObject right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator OpenAIPageableListOfMessageFileObject(string value) => new OpenAIPageableListOfMessageFileObject(value); + public static OpenAIPageableListOfVectorStoreObject List { get; } = new OpenAIPageableListOfVectorStoreObject(ListValue); + /// Determines if two values are the same. + public static bool operator ==(OpenAIPageableListOfVectorStoreObject left, OpenAIPageableListOfVectorStoreObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OpenAIPageableListOfVectorStoreObject left, OpenAIPageableListOfVectorStoreObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OpenAIPageableListOfVectorStoreObject(string value) => new OpenAIPageableListOfVectorStoreObject(value); /// [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is OpenAIPageableListOfMessageFileObject other && Equals(other); + public override bool Equals(object obj) => obj is OpenAIPageableListOfVectorStoreObject other && Equals(other); /// - public bool Equals(OpenAIPageableListOfMessageFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + public bool Equals(OpenAIPageableListOfVectorStoreObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); /// [EditorBrowsable(EditorBrowsableState.Never)] diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.cs deleted file mode 100644 index f2f39855b348..000000000000 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Assistants -{ - /// The input definition information for a retrieval tool as used to configure an assistant. - public partial class RetrievalToolDefinition : ToolDefinition - { - /// Initializes a new instance of . - public RetrievalToolDefinition() - { - Type = "retrieval"; - } - - /// Initializes a new instance of . - /// The object type. - /// Keeps track of any properties unknown to the library. - internal RetrievalToolDefinition(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.Serialization.cs new file mode 100644 index 000000000000..c7a00fd70182 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunCompletionUsage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunCompletionUsage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("completion_tokens"u8); + writer.WriteNumberValue(CompletionTokens); + writer.WritePropertyName("prompt_tokens"u8); + writer.WriteNumberValue(PromptTokens); + writer.WritePropertyName("total_tokens"u8); + writer.WriteNumberValue(TotalTokens); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunCompletionUsage 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(RunCompletionUsage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunCompletionUsage(document.RootElement, options); + } + + internal static RunCompletionUsage DeserializeRunCompletionUsage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + long completionTokens = default; + long promptTokens = default; + long totalTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("completion_tokens"u8)) + { + completionTokens = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("prompt_tokens"u8)) + { + promptTokens = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("total_tokens"u8)) + { + totalTokens = property.Value.GetInt64(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunCompletionUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData); + } + + 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(RunCompletionUsage)} does not support writing '{options.Format}' format."); + } + } + + RunCompletionUsage 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 DeserializeRunCompletionUsage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunCompletionUsage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunCompletionUsage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunCompletionUsage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.cs new file mode 100644 index 000000000000..2dfd3c2ee2c8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + public partial class RunCompletionUsage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run. + /// Number of prompt tokens used over the course of the run. + /// Total number of tokens used (prompt + completion). + internal RunCompletionUsage(long completionTokens, long promptTokens, long totalTokens) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + } + + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run. + /// Number of prompt tokens used over the course of the run. + /// Total number of tokens used (prompt + completion). + /// Keeps track of any properties unknown to the library. + internal RunCompletionUsage(long completionTokens, long promptTokens, long totalTokens, IDictionary serializedAdditionalRawData) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RunCompletionUsage() + { + } + + /// Number of completion tokens used over the course of the run. + public long CompletionTokens { get; } + /// Number of prompt tokens used over the course of the run. + public long PromptTokens { get; } + /// Total number of tokens used (prompt + completion). + public long TotalTokens { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.Serialization.cs index d1e90dfd8187..a1118659acac 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.Serialization.cs @@ -89,6 +89,18 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions o { writer.WriteNull("failed_at"); } + if (Optional.IsDefined(Usage)) + { + if (Usage != null) + { + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + } + else + { + writer.WriteNull("usage"); + } + } if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -156,6 +168,7 @@ internal static RunStep DeserializeRunStep(JsonElement element, ModelReaderWrite DateTimeOffset? completedAt = default; DateTimeOffset? cancelledAt = default; DateTimeOffset? failedAt = default; + RunStepCompletionUsage usage = default; IReadOnlyDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -236,6 +249,16 @@ internal static RunStep DeserializeRunStep(JsonElement element, ModelReaderWrite DeserializeNullableDateTimeOffset(property, ref failedAt); continue; } + if (property.NameEquals("usage"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + usage = null; + continue; + } + usage = RunStepCompletionUsage.DeserializeRunStepCompletionUsage(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -272,6 +295,7 @@ internal static RunStep DeserializeRunStep(JsonElement element, ModelReaderWrite completedAt, cancelledAt, failedAt, + usage, metadata, serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.cs index 9d8d21d55457..3b622f261eb6 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.cs @@ -108,9 +108,10 @@ internal RunStep(string id, RunStepType type, string assistantId, string threadI /// The Unix timestamp, in seconds, representing when this completed. /// The Unix timestamp, in seconds, representing when this was cancelled. /// The Unix timestamp, in seconds, representing when this failed. + /// Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal RunStep(string id, string @object, RunStepType type, string assistantId, string threadId, string runId, RunStepStatus status, RunStepDetails stepDetails, RunStepError lastError, DateTimeOffset createdAt, DateTimeOffset? expiredAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal RunStep(string id, string @object, RunStepType type, string assistantId, string threadId, string runId, RunStepStatus status, RunStepDetails stepDetails, RunStepError lastError, DateTimeOffset createdAt, DateTimeOffset? expiredAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, RunStepCompletionUsage usage, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; @@ -126,6 +127,7 @@ internal RunStep(string id, string @object, RunStepType type, string assistantId CompletedAt = completedAt; CancelledAt = cancelledAt; FailedAt = failedAt; + Usage = usage; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -166,6 +168,8 @@ internal RunStep() public DateTimeOffset? CancelledAt { get; } /// The Unix timestamp, in seconds, representing when this failed. public DateTimeOffset? FailedAt { get; } + /// Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`. + public RunStepCompletionUsage Usage { get; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IReadOnlyDictionary Metadata { get; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.Serialization.cs new file mode 100644 index 000000000000..11af2fe4c1ef --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepCompletionUsage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepCompletionUsage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("completion_tokens"u8); + writer.WriteNumberValue(CompletionTokens); + writer.WritePropertyName("prompt_tokens"u8); + writer.WriteNumberValue(PromptTokens); + writer.WritePropertyName("total_tokens"u8); + writer.WriteNumberValue(TotalTokens); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepCompletionUsage 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(RunStepCompletionUsage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepCompletionUsage(document.RootElement, options); + } + + internal static RunStepCompletionUsage DeserializeRunStepCompletionUsage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + long completionTokens = default; + long promptTokens = default; + long totalTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("completion_tokens"u8)) + { + completionTokens = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("prompt_tokens"u8)) + { + promptTokens = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("total_tokens"u8)) + { + totalTokens = property.Value.GetInt64(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepCompletionUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData); + } + + 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(RunStepCompletionUsage)} does not support writing '{options.Format}' format."); + } + } + + RunStepCompletionUsage 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 DeserializeRunStepCompletionUsage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepCompletionUsage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepCompletionUsage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepCompletionUsage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.cs new file mode 100644 index 000000000000..738d57f0df80 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Usage statistics related to the run step. + public partial class RunStepCompletionUsage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run step. + /// Number of prompt tokens used over the course of the run step. + /// Total number of tokens used (prompt + completion). + internal RunStepCompletionUsage(long completionTokens, long promptTokens, long totalTokens) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + } + + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run step. + /// Number of prompt tokens used over the course of the run step. + /// Total number of tokens used (prompt + completion). + /// Keeps track of any properties unknown to the library. + internal RunStepCompletionUsage(long completionTokens, long promptTokens, long totalTokens, IDictionary serializedAdditionalRawData) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RunStepCompletionUsage() + { + } + + /// Number of completion tokens used over the course of the run step. + public long CompletionTokens { get; } + /// Number of prompt tokens used over the course of the run step. + public long PromptTokens { get; } + /// Total number of tokens used (prompt + completion). + public long TotalTokens { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.Serialization.cs new file mode 100644 index 000000000000..aa432bbe3d8d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDelta : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDelta)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(StepDetails)) + { + writer.WritePropertyName("step_details"u8); + writer.WriteObjectValue(StepDetails, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDelta 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(RunStepDelta)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDelta(document.RootElement, options); + } + + internal static RunStepDelta DeserializeRunStepDelta(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RunStepDeltaDetail stepDetails = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("step_details"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stepDetails = RunStepDeltaDetail.DeserializeRunStepDeltaDetail(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDelta(stepDetails, serializedAdditionalRawData); + } + + 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(RunStepDelta)} does not support writing '{options.Format}' format."); + } + } + + RunStepDelta 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 DeserializeRunStepDelta(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDelta)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDelta FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDelta(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.cs new file mode 100644 index 000000000000..9b28f292c68b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the delta payload in a streaming run step delta chunk. + public partial class RunStepDelta + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal RunStepDelta() + { + } + + /// Initializes a new instance of . + /// + /// The details of the run step. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal RunStepDelta(RunStepDeltaDetail stepDetails, IDictionary serializedAdditionalRawData) + { + StepDetails = stepDetails; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The details of the run step. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public RunStepDeltaDetail StepDetails { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.Serialization.cs new file mode 100644 index 000000000000..2aa656e530bb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaChunk : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaChunk)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("delta"u8); + writer.WriteObjectValue(Delta, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaChunk 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(RunStepDeltaChunk)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaChunk(document.RootElement, options); + } + + internal static RunStepDeltaChunk DeserializeRunStepDeltaChunk(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + RunStepDeltaChunkObject @object = default; + RunStepDelta delta = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new RunStepDeltaChunkObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("delta"u8)) + { + delta = RunStepDelta.DeserializeRunStepDelta(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaChunk(id, @object, delta, serializedAdditionalRawData); + } + + 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(RunStepDeltaChunk)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaChunk 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 DeserializeRunStepDeltaChunk(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaChunk)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaChunk FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaChunk(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.cs new file mode 100644 index 000000000000..b577dd0a9f7d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a run step delta i.e. any changed fields on a run step during streaming. + public partial class RunStepDeltaChunk + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The identifier of the run step, which can be referenced in API endpoints. + /// The delta containing the fields that have changed on the run step. + /// or is null. + internal RunStepDeltaChunk(string id, RunStepDelta delta) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(delta, nameof(delta)); + + Id = id; + Delta = delta; + } + + /// Initializes a new instance of . + /// The identifier of the run step, which can be referenced in API endpoints. + /// The object type, which is always `thread.run.step.delta`. + /// The delta containing the fields that have changed on the run step. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaChunk(string id, RunStepDeltaChunkObject @object, RunStepDelta delta, IDictionary serializedAdditionalRawData) + { + Id = id; + Object = @object; + Delta = delta; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaChunk() + { + } + + /// The identifier of the run step, which can be referenced in API endpoints. + public string Id { get; } + /// The object type, which is always `thread.run.step.delta`. + public RunStepDeltaChunkObject Object { get; } = RunStepDeltaChunkObject.ThreadRunStepDelta; + + /// The delta containing the fields that have changed on the run step. + public RunStepDelta Delta { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunkObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunkObject.cs new file mode 100644 index 000000000000..4cadb42a2b35 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunkObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The RunStepDeltaChunk_object. + public readonly partial struct RunStepDeltaChunkObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RunStepDeltaChunkObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadRunStepDeltaValue = "thread.run.step.delta"; + + /// thread.run.step.delta. + public static RunStepDeltaChunkObject ThreadRunStepDelta { get; } = new RunStepDeltaChunkObject(ThreadRunStepDeltaValue); + /// Determines if two values are the same. + public static bool operator ==(RunStepDeltaChunkObject left, RunStepDeltaChunkObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RunStepDeltaChunkObject left, RunStepDeltaChunkObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator RunStepDeltaChunkObject(string value) => new RunStepDeltaChunkObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RunStepDeltaChunkObject other && Equals(other); + /// + public bool Equals(RunStepDeltaChunkObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.Serialization.cs new file mode 100644 index 000000000000..5e994dae2f13 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.Serialization.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaCodeInterpreterDetailItemObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaCodeInterpreterDetailItemObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Input)) + { + writer.WritePropertyName("input"u8); + writer.WriteStringValue(Input); + } + if (Optional.IsCollectionDefined(Outputs)) + { + writer.WritePropertyName("outputs"u8); + writer.WriteStartArray(); + foreach (var item in Outputs) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaCodeInterpreterDetailItemObject 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(RunStepDeltaCodeInterpreterDetailItemObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterDetailItemObject(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterDetailItemObject DeserializeRunStepDeltaCodeInterpreterDetailItemObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string input = default; + IReadOnlyList outputs = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("input"u8)) + { + input = property.Value.GetString(); + continue; + } + if (property.NameEquals("outputs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(RunStepDeltaCodeInterpreterOutput.DeserializeRunStepDeltaCodeInterpreterOutput(item, options)); + } + outputs = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaCodeInterpreterDetailItemObject(input, outputs ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + 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(RunStepDeltaCodeInterpreterDetailItemObject)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterDetailItemObject 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 DeserializeRunStepDeltaCodeInterpreterDetailItemObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterDetailItemObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaCodeInterpreterDetailItemObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaCodeInterpreterDetailItemObject(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.cs new file mode 100644 index 000000000000..d3a655d903d0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the Code Interpreter tool call data in a streaming run step's tool calls. + public partial class RunStepDeltaCodeInterpreterDetailItemObject + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal RunStepDeltaCodeInterpreterDetailItemObject() + { + Outputs = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The input into the Code Interpreter tool call. + /// + /// The outputs from the Code Interpreter tool call. Code Interpreter can output one or more + /// items, including text (`logs`) or images (`image`). Each of these are represented by a + /// different object type. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaCodeInterpreterDetailItemObject(string input, IReadOnlyList outputs, IDictionary serializedAdditionalRawData) + { + Input = input; + Outputs = outputs; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The input into the Code Interpreter tool call. + public string Input { get; } + /// + /// The outputs from the Code Interpreter tool call. Code Interpreter can output one or more + /// items, including text (`logs`) or images (`image`). Each of these are represented by a + /// different object type. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public IReadOnlyList Outputs { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.Serialization.cs new file mode 100644 index 000000000000..d04aca3ea636 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaCodeInterpreterImageOutput : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaCodeInterpreterImageOutput)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Image)) + { + writer.WritePropertyName("image"u8); + writer.WriteObjectValue(Image, options); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaCodeInterpreterImageOutput 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(RunStepDeltaCodeInterpreterImageOutput)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterImageOutput(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterImageOutput DeserializeRunStepDeltaCodeInterpreterImageOutput(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RunStepDeltaCodeInterpreterImageOutputObject image = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("image"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + image = RunStepDeltaCodeInterpreterImageOutputObject.DeserializeRunStepDeltaCodeInterpreterImageOutputObject(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaCodeInterpreterImageOutput(index, type, serializedAdditionalRawData, image); + } + + 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(RunStepDeltaCodeInterpreterImageOutput)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterImageOutput 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 DeserializeRunStepDeltaCodeInterpreterImageOutput(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterImageOutput)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaCodeInterpreterImageOutput FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaCodeInterpreterImageOutput(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.cs new file mode 100644 index 000000000000..0d80fac4887c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents an image output as produced the Code interpreter tool and as represented in a streaming run step's delta tool calls collection. + public partial class RunStepDeltaCodeInterpreterImageOutput : RunStepDeltaCodeInterpreterOutput + { + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + internal RunStepDeltaCodeInterpreterImageOutput(int index) : base(index) + { + Type = "image"; + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The type of the streaming run step tool call's Code Interpreter output. + /// Keeps track of any properties unknown to the library. + /// The image data for the Code Interpreter tool call output. + internal RunStepDeltaCodeInterpreterImageOutput(int index, string type, IDictionary serializedAdditionalRawData, RunStepDeltaCodeInterpreterImageOutputObject image) : base(index, type, serializedAdditionalRawData) + { + Image = image; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaCodeInterpreterImageOutput() + { + } + + /// The image data for the Code Interpreter tool call output. + public RunStepDeltaCodeInterpreterImageOutputObject Image { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.Serialization.cs new file mode 100644 index 000000000000..9322d0b4b1ee --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.Serialization.cs @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaCodeInterpreterImageOutputObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaCodeInterpreterImageOutputObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(FileId)) + { + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaCodeInterpreterImageOutputObject 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(RunStepDeltaCodeInterpreterImageOutputObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterImageOutputObject(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterImageOutputObject DeserializeRunStepDeltaCodeInterpreterImageOutputObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaCodeInterpreterImageOutputObject(fileId, serializedAdditionalRawData); + } + + 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(RunStepDeltaCodeInterpreterImageOutputObject)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterImageOutputObject 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 DeserializeRunStepDeltaCodeInterpreterImageOutputObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterImageOutputObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaCodeInterpreterImageOutputObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaCodeInterpreterImageOutputObject(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/RequestContentFilterResult.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.cs similarity index 62% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/RequestContentFilterResult.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.cs index 74a54e0155bb..35c4bf8d080b 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/RequestContentFilterResult.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -5,10 +8,10 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI +namespace Azure.AI.OpenAI.Assistants { - /// A content filter result associated with a single input prompt item into a generative AI system. - public partial class RequestContentFilterResult + /// Represents the data for a streaming run step's Code Interpreter tool call image output. + public partial class RunStepDeltaCodeInterpreterImageOutputObject { /// /// Keeps track of any properties unknown to the library. @@ -40,21 +43,23 @@ public partial class RequestContentFilterResult /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal RequestContentFilterResult() + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal RunStepDeltaCodeInterpreterImageOutputObject() { } - /// Initializes a new instance of . - /// The index of the input prompt associated with the accompanying content filter result categories. - /// The content filter category details for the result. + /// Initializes a new instance of . + /// The file ID for the image. /// Keeps track of any properties unknown to the library. - internal RequestContentFilterResult(int? promptIndex, InternalAzureContentFilterResultForPromptContentFilterResults internalResults, IDictionary serializedAdditionalRawData) + internal RunStepDeltaCodeInterpreterImageOutputObject(string fileId, IDictionary serializedAdditionalRawData) { - PromptIndex = promptIndex; - InternalResults = internalResults; - SerializedAdditionalRawData = serializedAdditionalRawData; + FileId = fileId; + _serializedAdditionalRawData = serializedAdditionalRawData; } + + /// The file ID for the image. + public string FileId { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.Serialization.cs new file mode 100644 index 000000000000..bb764ac22b70 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.Serialization.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaCodeInterpreterLogOutput : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaCodeInterpreterLogOutput)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Logs)) + { + writer.WritePropertyName("logs"u8); + writer.WriteStringValue(Logs); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaCodeInterpreterLogOutput 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(RunStepDeltaCodeInterpreterLogOutput)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterLogOutput(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterLogOutput DeserializeRunStepDeltaCodeInterpreterLogOutput(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string logs = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("logs"u8)) + { + logs = property.Value.GetString(); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaCodeInterpreterLogOutput(index, type, serializedAdditionalRawData, logs); + } + + 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(RunStepDeltaCodeInterpreterLogOutput)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterLogOutput 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 DeserializeRunStepDeltaCodeInterpreterLogOutput(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterLogOutput)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaCodeInterpreterLogOutput FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaCodeInterpreterLogOutput(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.cs new file mode 100644 index 000000000000..96eaa7b38dc3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a log output as produced by the Code Interpreter tool and as represented in a streaming run step's delta tool calls collection. + public partial class RunStepDeltaCodeInterpreterLogOutput : RunStepDeltaCodeInterpreterOutput + { + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + internal RunStepDeltaCodeInterpreterLogOutput(int index) : base(index) + { + Type = "logs"; + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The type of the streaming run step tool call's Code Interpreter output. + /// Keeps track of any properties unknown to the library. + /// The text output from the Code Interpreter tool call. + internal RunStepDeltaCodeInterpreterLogOutput(int index, string type, IDictionary serializedAdditionalRawData, string logs) : base(index, type, serializedAdditionalRawData) + { + Logs = logs; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaCodeInterpreterLogOutput() + { + } + + /// The text output from the Code Interpreter tool call. + public string Logs { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.Serialization.cs new file mode 100644 index 000000000000..6e213cb7d63f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.Serialization.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownRunStepDeltaCodeInterpreterOutput))] + public partial class RunStepDeltaCodeInterpreterOutput : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaCodeInterpreterOutput)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaCodeInterpreterOutput 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(RunStepDeltaCodeInterpreterOutput)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterOutput(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterOutput DeserializeRunStepDeltaCodeInterpreterOutput(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "image": return RunStepDeltaCodeInterpreterImageOutput.DeserializeRunStepDeltaCodeInterpreterImageOutput(element, options); + case "logs": return RunStepDeltaCodeInterpreterLogOutput.DeserializeRunStepDeltaCodeInterpreterLogOutput(element, options); + } + } + return UnknownRunStepDeltaCodeInterpreterOutput.DeserializeUnknownRunStepDeltaCodeInterpreterOutput(element, 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(RunStepDeltaCodeInterpreterOutput)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterOutput 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 DeserializeRunStepDeltaCodeInterpreterOutput(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterOutput)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaCodeInterpreterOutput FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaCodeInterpreterOutput(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.cs new file mode 100644 index 000000000000..396e993239ce --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// The abstract base representation of a streaming run step tool call's Code Interpreter tool output. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class RunStepDeltaCodeInterpreterOutput + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + protected RunStepDeltaCodeInterpreterOutput(int index) + { + Index = index; + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The type of the streaming run step tool call's Code Interpreter output. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaCodeInterpreterOutput(int index, string type, IDictionary serializedAdditionalRawData) + { + Index = index; + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaCodeInterpreterOutput() + { + } + + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + public int Index { get; } + /// The type of the streaming run step tool call's Code Interpreter output. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.Serialization.cs new file mode 100644 index 000000000000..1daa8feffe07 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.Serialization.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaCodeInterpreterToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaCodeInterpreterToolCall)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(CodeInterpreter)) + { + writer.WritePropertyName("code_interpreter"u8); + writer.WriteObjectValue(CodeInterpreter, options); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaCodeInterpreterToolCall 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(RunStepDeltaCodeInterpreterToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterToolCall(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterToolCall DeserializeRunStepDeltaCodeInterpreterToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RunStepDeltaCodeInterpreterDetailItemObject codeInterpreter = default; + int index = default; + string id = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code_interpreter"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + codeInterpreter = RunStepDeltaCodeInterpreterDetailItemObject.DeserializeRunStepDeltaCodeInterpreterDetailItemObject(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaCodeInterpreterToolCall(index, id, type, serializedAdditionalRawData, codeInterpreter); + } + + 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(RunStepDeltaCodeInterpreterToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterToolCall 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 DeserializeRunStepDeltaCodeInterpreterToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaCodeInterpreterToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaCodeInterpreterToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.cs new file mode 100644 index 000000000000..059c30cbca81 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a Code Interpreter tool call within a streaming run step's tool call details. + public partial class RunStepDeltaCodeInterpreterToolCall : RunStepDeltaToolCall + { + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// is null. + internal RunStepDeltaCodeInterpreterToolCall(int index, string id) : base(index, id) + { + Argument.AssertNotNull(id, nameof(id)); + + Type = "code_interpreter"; + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// Keeps track of any properties unknown to the library. + /// The Code Interpreter data for the tool call. + internal RunStepDeltaCodeInterpreterToolCall(int index, string id, string type, IDictionary serializedAdditionalRawData, RunStepDeltaCodeInterpreterDetailItemObject codeInterpreter) : base(index, id, type, serializedAdditionalRawData) + { + CodeInterpreter = codeInterpreter; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaCodeInterpreterToolCall() + { + } + + /// The Code Interpreter data for the tool call. + public RunStepDeltaCodeInterpreterDetailItemObject CodeInterpreter { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.Serialization.cs new file mode 100644 index 000000000000..274b792c2227 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.Serialization.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownRunStepDeltaDetail))] + public partial class RunStepDeltaDetail : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaDetail)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaDetail 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(RunStepDeltaDetail)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaDetail(document.RootElement, options); + } + + internal static RunStepDeltaDetail DeserializeRunStepDeltaDetail(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "message_creation": return RunStepDeltaMessageCreation.DeserializeRunStepDeltaMessageCreation(element, options); + case "tool_calls": return RunStepDeltaToolCallObject.DeserializeRunStepDeltaToolCallObject(element, options); + } + } + return UnknownRunStepDeltaDetail.DeserializeUnknownRunStepDeltaDetail(element, 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(RunStepDeltaDetail)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaDetail 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 DeserializeRunStepDeltaDetail(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaDetail)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaDetail FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaDetail(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceVectorizer.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.cs similarity index 55% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceVectorizer.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.cs index 474c2459025b..508fac38660c 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceVectorizer.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -5,13 +8,14 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI.Assistants { /// - /// A representation of a data vectorization source usable as an embedding resource with a data source. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. + /// Represents a single run step detail item in a streaming run step's delta payload. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . /// - public abstract partial class DataSourceVectorizer + public abstract partial class RunStepDeltaDetail { /// /// Keeps track of any properties unknown to the library. @@ -43,22 +47,23 @@ public abstract partial class DataSourceVectorizer /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - protected DataSourceVectorizer() + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected RunStepDeltaDetail() { } - /// Initializes a new instance of . - /// The differentiating identifier for the concrete vectorization source. + /// Initializes a new instance of . + /// The object type for the run step detail object. /// Keeps track of any properties unknown to the library. - internal DataSourceVectorizer(string type, IDictionary serializedAdditionalRawData) + internal RunStepDeltaDetail(string type, IDictionary serializedAdditionalRawData) { Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// The differentiating identifier for the concrete vectorization source. + /// The object type for the run step detail object. internal string Type { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.Serialization.cs new file mode 100644 index 000000000000..bfbb55ddae92 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.Serialization.cs @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaFileSearchToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaFileSearchToolCall)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsCollectionDefined(FileSearch)) + { + writer.WritePropertyName("file_search"u8); + writer.WriteStartObject(); + foreach (var item in FileSearch) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaFileSearchToolCall 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(RunStepDeltaFileSearchToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaFileSearchToolCall(document.RootElement, options); + } + + internal static RunStepDeltaFileSearchToolCall DeserializeRunStepDeltaFileSearchToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyDictionary fileSearch = default; + int index = default; + string id = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_search"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + fileSearch = dictionary; + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaFileSearchToolCall(index, id, type, serializedAdditionalRawData, fileSearch ?? new ChangeTrackingDictionary()); + } + + 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(RunStepDeltaFileSearchToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaFileSearchToolCall 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 DeserializeRunStepDeltaFileSearchToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaFileSearchToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaFileSearchToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaFileSearchToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.cs new file mode 100644 index 000000000000..7be515d9cc76 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a file search tool call within a streaming run step's tool call details. + public partial class RunStepDeltaFileSearchToolCall : RunStepDeltaToolCall + { + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// is null. + internal RunStepDeltaFileSearchToolCall(int index, string id) : base(index, id) + { + Argument.AssertNotNull(id, nameof(id)); + + Type = "file_search"; + FileSearch = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// Keeps track of any properties unknown to the library. + /// Reserved for future use. + internal RunStepDeltaFileSearchToolCall(int index, string id, string type, IDictionary serializedAdditionalRawData, IReadOnlyDictionary fileSearch) : base(index, id, type, serializedAdditionalRawData) + { + FileSearch = fileSearch; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaFileSearchToolCall() + { + } + + /// Reserved for future use. + public IReadOnlyDictionary FileSearch { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.Serialization.cs new file mode 100644 index 000000000000..e1f73cd20f39 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.Serialization.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaFunction : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaFunction)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (Optional.IsDefined(Arguments)) + { + writer.WritePropertyName("arguments"u8); + writer.WriteStringValue(Arguments); + } + if (Optional.IsDefined(Output)) + { + if (Output != null) + { + writer.WritePropertyName("output"u8); + writer.WriteStringValue(Output); + } + else + { + writer.WriteNull("output"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaFunction 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(RunStepDeltaFunction)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaFunction(document.RootElement, options); + } + + internal static RunStepDeltaFunction DeserializeRunStepDeltaFunction(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string arguments = default; + string output = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("arguments"u8)) + { + arguments = property.Value.GetString(); + continue; + } + if (property.NameEquals("output"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + output = null; + continue; + } + output = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaFunction(name, arguments, output, serializedAdditionalRawData); + } + + 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(RunStepDeltaFunction)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaFunction 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 DeserializeRunStepDeltaFunction(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaFunction)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaFunction FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaFunction(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.cs new file mode 100644 index 000000000000..df34c88e6f43 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the function data in a streaming run step delta's function tool call. + public partial class RunStepDeltaFunction + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal RunStepDeltaFunction() + { + } + + /// Initializes a new instance of . + /// The name of the function. + /// The arguments passed to the function as input. + /// The output of the function, null if outputs have not yet been submitted. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaFunction(string name, string arguments, string output, IDictionary serializedAdditionalRawData) + { + Name = name; + Arguments = arguments; + Output = output; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The name of the function. + public string Name { get; } + /// The arguments passed to the function as input. + public string Arguments { get; } + /// The output of the function, null if outputs have not yet been submitted. + public string Output { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.Serialization.cs new file mode 100644 index 000000000000..43ebba310262 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.Serialization.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaFunctionToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaFunctionToolCall)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Function)) + { + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaFunctionToolCall 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(RunStepDeltaFunctionToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaFunctionToolCall(document.RootElement, options); + } + + internal static RunStepDeltaFunctionToolCall DeserializeRunStepDeltaFunctionToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RunStepDeltaFunction function = default; + int index = default; + string id = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("function"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + function = RunStepDeltaFunction.DeserializeRunStepDeltaFunction(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaFunctionToolCall(index, id, type, serializedAdditionalRawData, function); + } + + 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(RunStepDeltaFunctionToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaFunctionToolCall 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 DeserializeRunStepDeltaFunctionToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaFunctionToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaFunctionToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaFunctionToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.cs new file mode 100644 index 000000000000..ce9d9486ef82 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a function tool call within a streaming run step's tool call details. + public partial class RunStepDeltaFunctionToolCall : RunStepDeltaToolCall + { + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// is null. + internal RunStepDeltaFunctionToolCall(int index, string id) : base(index, id) + { + Argument.AssertNotNull(id, nameof(id)); + + Type = "function"; + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// Keeps track of any properties unknown to the library. + /// The function data for the tool call. + internal RunStepDeltaFunctionToolCall(int index, string id, string type, IDictionary serializedAdditionalRawData, RunStepDeltaFunction function) : base(index, id, type, serializedAdditionalRawData) + { + Function = function; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaFunctionToolCall() + { + } + + /// The function data for the tool call. + public RunStepDeltaFunction Function { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.Serialization.cs new file mode 100644 index 000000000000..e526f0766540 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaMessageCreation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaMessageCreation)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(MessageCreation)) + { + writer.WritePropertyName("message_creation"u8); + writer.WriteObjectValue(MessageCreation, options); + } + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaMessageCreation 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(RunStepDeltaMessageCreation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaMessageCreation(document.RootElement, options); + } + + internal static RunStepDeltaMessageCreation DeserializeRunStepDeltaMessageCreation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RunStepDeltaMessageCreationObject messageCreation = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("message_creation"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + messageCreation = RunStepDeltaMessageCreationObject.DeserializeRunStepDeltaMessageCreationObject(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaMessageCreation(type, serializedAdditionalRawData, messageCreation); + } + + 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(RunStepDeltaMessageCreation)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaMessageCreation 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 DeserializeRunStepDeltaMessageCreation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaMessageCreation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaMessageCreation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaMessageCreation(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.cs new file mode 100644 index 000000000000..38f8a808eeac --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.cs @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a message creation within a streaming run step delta. + public partial class RunStepDeltaMessageCreation : RunStepDeltaDetail + { + /// Initializes a new instance of . + internal RunStepDeltaMessageCreation() + { + Type = "message_creation"; + } + + /// Initializes a new instance of . + /// The object type for the run step detail object. + /// Keeps track of any properties unknown to the library. + /// The message creation data. + internal RunStepDeltaMessageCreation(string type, IDictionary serializedAdditionalRawData, RunStepDeltaMessageCreationObject messageCreation) : base(type, serializedAdditionalRawData) + { + MessageCreation = messageCreation; + } + + /// The message creation data. + public RunStepDeltaMessageCreationObject MessageCreation { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.Serialization.cs new file mode 100644 index 000000000000..58a72a5f6dc7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.Serialization.cs @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaMessageCreationObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaMessageCreationObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(MessageId)) + { + writer.WritePropertyName("message_id"u8); + writer.WriteStringValue(MessageId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaMessageCreationObject 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(RunStepDeltaMessageCreationObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaMessageCreationObject(document.RootElement, options); + } + + internal static RunStepDeltaMessageCreationObject DeserializeRunStepDeltaMessageCreationObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string messageId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("message_id"u8)) + { + messageId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaMessageCreationObject(messageId, serializedAdditionalRawData); + } + + 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(RunStepDeltaMessageCreationObject)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaMessageCreationObject 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 DeserializeRunStepDeltaMessageCreationObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaMessageCreationObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaMessageCreationObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaMessageCreationObject(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.cs new file mode 100644 index 000000000000..15aaccdbc60c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the data within a streaming run step message creation response object. + public partial class RunStepDeltaMessageCreationObject + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal RunStepDeltaMessageCreationObject() + { + } + + /// Initializes a new instance of . + /// The ID of the newly-created message. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaMessageCreationObject(string messageId, IDictionary serializedAdditionalRawData) + { + MessageId = messageId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The ID of the newly-created message. + public string MessageId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.Serialization.cs new file mode 100644 index 000000000000..90c180755ad5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.Serialization.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownRunStepDeltaToolCall))] + public partial class RunStepDeltaToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaToolCall)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaToolCall 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(RunStepDeltaToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaToolCall(document.RootElement, options); + } + + internal static RunStepDeltaToolCall DeserializeRunStepDeltaToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "code_interpreter": return RunStepDeltaCodeInterpreterToolCall.DeserializeRunStepDeltaCodeInterpreterToolCall(element, options); + case "file_search": return RunStepDeltaFileSearchToolCall.DeserializeRunStepDeltaFileSearchToolCall(element, options); + case "function": return RunStepDeltaFunctionToolCall.DeserializeRunStepDeltaFunctionToolCall(element, options); + } + } + return UnknownRunStepDeltaToolCall.DeserializeUnknownRunStepDeltaToolCall(element, 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(RunStepDeltaToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaToolCall 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 DeserializeRunStepDeltaToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaToolCall(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.cs new file mode 100644 index 000000000000..c056ec5693c5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// The abstract base representation of a single tool call within a streaming run step's delta tool call details. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public abstract partial class RunStepDeltaToolCall + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// is null. + protected RunStepDeltaToolCall(int index, string id) + { + Argument.AssertNotNull(id, nameof(id)); + + Index = index; + Id = id; + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaToolCall(int index, string id, string type, IDictionary serializedAdditionalRawData) + { + Index = index; + Id = id; + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaToolCall() + { + } + + /// The index of the tool call detail in the run step's tool_calls array. + public int Index { get; } + /// The ID of the tool call, used when submitting outputs to the run. + public string Id { get; } + /// The type of the tool call detail item in a streaming run step's details. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.Serialization.cs new file mode 100644 index 000000000000..19a2a33bf278 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaToolCallObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaToolCallObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsCollectionDefined(ToolCalls)) + { + writer.WritePropertyName("tool_calls"u8); + writer.WriteStartArray(); + foreach (var item in ToolCalls) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaToolCallObject 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(RunStepDeltaToolCallObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaToolCallObject(document.RootElement, options); + } + + internal static RunStepDeltaToolCallObject DeserializeRunStepDeltaToolCallObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList toolCalls = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(RunStepDeltaToolCall.DeserializeRunStepDeltaToolCall(item, options)); + } + toolCalls = array; + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaToolCallObject(type, serializedAdditionalRawData, toolCalls ?? new ChangeTrackingList()); + } + + 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(RunStepDeltaToolCallObject)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaToolCallObject 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 DeserializeRunStepDeltaToolCallObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaToolCallObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaToolCallObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeRunStepDeltaToolCallObject(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.cs new file mode 100644 index 000000000000..77d87fe333e1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents an invocation of tool calls as part of a streaming run step. + public partial class RunStepDeltaToolCallObject : RunStepDeltaDetail + { + /// Initializes a new instance of . + internal RunStepDeltaToolCallObject() + { + Type = "tool_calls"; + ToolCalls = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The object type for the run step detail object. + /// Keeps track of any properties unknown to the library. + /// + /// The collection of tool calls for the tool call detail item. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + internal RunStepDeltaToolCallObject(string type, IDictionary serializedAdditionalRawData, IReadOnlyList toolCalls) : base(type, serializedAdditionalRawData) + { + ToolCalls = toolCalls; + } + + /// + /// The collection of tool calls for the tool call detail item. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public IReadOnlyList ToolCalls { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.Serialization.cs similarity index 66% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.Serialization.cs index ab165de44e9d..cd7d7b80f371 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.Serialization.cs @@ -13,22 +13,22 @@ namespace Azure.AI.OpenAI.Assistants { - public partial class RunStepRetrievalToolCall : IUtf8JsonSerializable, IJsonModel + public partial class RunStepFileSearchToolCall : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(RunStepRetrievalToolCall)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(RunStepFileSearchToolCall)} does not support writing '{format}' format."); } writer.WriteStartObject(); - writer.WritePropertyName("retrieval"u8); + writer.WritePropertyName("file_search"u8); writer.WriteStartObject(); - foreach (var item in Retrieval) + foreach (var item in FileSearch) { writer.WritePropertyName(item.Key); writer.WriteStringValue(item.Value); @@ -56,19 +56,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead writer.WriteEndObject(); } - RunStepRetrievalToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + RunStepFileSearchToolCall 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(RunStepRetrievalToolCall)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(RunStepFileSearchToolCall)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeRunStepRetrievalToolCall(document.RootElement, options); + return DeserializeRunStepFileSearchToolCall(document.RootElement, options); } - internal static RunStepRetrievalToolCall DeserializeRunStepRetrievalToolCall(JsonElement element, ModelReaderWriterOptions options = null) + internal static RunStepFileSearchToolCall DeserializeRunStepFileSearchToolCall(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -76,21 +76,21 @@ internal static RunStepRetrievalToolCall DeserializeRunStepRetrievalToolCall(Jso { return null; } - IReadOnlyDictionary retrieval = default; + IReadOnlyDictionary fileSearch = default; string type = default; string id = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("retrieval"u8)) + if (property.NameEquals("file_search"u8)) { Dictionary dictionary = new Dictionary(); foreach (var property0 in property.Value.EnumerateObject()) { dictionary.Add(property0.Name, property0.Value.GetString()); } - retrieval = dictionary; + fileSearch = dictionary; continue; } if (property.NameEquals("type"u8)) @@ -109,46 +109,46 @@ internal static RunStepRetrievalToolCall DeserializeRunStepRetrievalToolCall(Jso } } serializedAdditionalRawData = rawDataDictionary; - return new RunStepRetrievalToolCall(type, id, serializedAdditionalRawData, retrieval); + return new RunStepFileSearchToolCall(type, id, serializedAdditionalRawData, fileSearch); } - 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(RunStepRetrievalToolCall)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(RunStepFileSearchToolCall)} does not support writing '{options.Format}' format."); } } - RunStepRetrievalToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + RunStepFileSearchToolCall 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 DeserializeRunStepRetrievalToolCall(document.RootElement, options); + return DeserializeRunStepFileSearchToolCall(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(RunStepRetrievalToolCall)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(RunStepFileSearchToolCall)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static new RunStepRetrievalToolCall FromResponse(Response response) + internal static new RunStepFileSearchToolCall FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeRunStepRetrievalToolCall(document.RootElement); + return DeserializeRunStepFileSearchToolCall(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.cs new file mode 100644 index 000000000000..0b3014e92127 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// A record of a call to a file search tool, issued by the model in evaluation of a defined tool, that represents + /// executed file search. + /// + public partial class RunStepFileSearchToolCall : RunStepToolCall + { + /// Initializes a new instance of . + /// The ID of the tool call. This ID must be referenced when you submit tool outputs. + /// Reserved for future use. + /// or is null. + internal RunStepFileSearchToolCall(string id, IReadOnlyDictionary fileSearch) : base(id) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(fileSearch, nameof(fileSearch)); + + Type = "file_search"; + FileSearch = fileSearch; + } + + /// Initializes a new instance of . + /// The object type. + /// The ID of the tool call. This ID must be referenced when you submit tool outputs. + /// Keeps track of any properties unknown to the library. + /// Reserved for future use. + internal RunStepFileSearchToolCall(string type, string id, IDictionary serializedAdditionalRawData, IReadOnlyDictionary fileSearch) : base(type, id, serializedAdditionalRawData) + { + FileSearch = fileSearch; + } + + /// Initializes a new instance of for deserialization. + internal RunStepFileSearchToolCall() + { + } + + /// Reserved for future use. + public IReadOnlyDictionary FileSearch { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.cs deleted file mode 100644 index 5f119347d5f3..000000000000 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Assistants -{ - /// - /// A record of a call to a retrieval tool, issued by the model in evaluation of a defined tool, that represents - /// executed retrieval actions. - /// - public partial class RunStepRetrievalToolCall : RunStepToolCall - { - /// Initializes a new instance of . - /// The ID of the tool call. This ID must be referenced when you submit tool outputs. - /// The key/value pairs produced by the retrieval tool. - /// or is null. - internal RunStepRetrievalToolCall(string id, IReadOnlyDictionary retrieval) : base(id) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(retrieval, nameof(retrieval)); - - Type = "retrieval"; - Retrieval = retrieval; - } - - /// Initializes a new instance of . - /// The object type. - /// The ID of the tool call. This ID must be referenced when you submit tool outputs. - /// Keeps track of any properties unknown to the library. - /// The key/value pairs produced by the retrieval tool. - internal RunStepRetrievalToolCall(string type, string id, IDictionary serializedAdditionalRawData, IReadOnlyDictionary retrieval) : base(type, id, serializedAdditionalRawData) - { - Retrieval = retrieval; - } - - /// Initializes a new instance of for deserialization. - internal RunStepRetrievalToolCall() - { - } - - /// The key/value pairs produced by the retrieval tool. - public IReadOnlyDictionary Retrieval { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepStreamEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepStreamEvent.cs new file mode 100644 index 000000000000..3949704709ad --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepStreamEvent.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Run step operation related streaming events. + public readonly partial struct RunStepStreamEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RunStepStreamEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadRunStepCreatedValue = "thread.run.step.created"; + private const string ThreadRunStepInProgressValue = "thread.run.step.in_progress"; + private const string ThreadRunStepDeltaValue = "thread.run.step.delta"; + private const string ThreadRunStepCompletedValue = "thread.run.step.completed"; + private const string ThreadRunStepFailedValue = "thread.run.step.failed"; + private const string ThreadRunStepCancelledValue = "thread.run.step.cancelled"; + private const string ThreadRunStepExpiredValue = "thread.run.step.expired"; + + /// Event sent when a new thread run step is created. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepCreated { get; } = new RunStepStreamEvent(ThreadRunStepCreatedValue); + /// Event sent when a run step moves to `in_progress` status. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepInProgress { get; } = new RunStepStreamEvent(ThreadRunStepInProgressValue); + /// Event sent when a run stepis being streamed. The data of this event is of type RunStepDeltaChunk. + public static RunStepStreamEvent ThreadRunStepDelta { get; } = new RunStepStreamEvent(ThreadRunStepDeltaValue); + /// Event sent when a run step is completed. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepCompleted { get; } = new RunStepStreamEvent(ThreadRunStepCompletedValue); + /// Event sent when a run step fails. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepFailed { get; } = new RunStepStreamEvent(ThreadRunStepFailedValue); + /// Event sent when a run step is cancelled. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepCancelled { get; } = new RunStepStreamEvent(ThreadRunStepCancelledValue); + /// Event sent when a run step is expired. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepExpired { get; } = new RunStepStreamEvent(ThreadRunStepExpiredValue); + /// Determines if two values are the same. + public static bool operator ==(RunStepStreamEvent left, RunStepStreamEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RunStepStreamEvent left, RunStepStreamEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator RunStepStreamEvent(string value) => new RunStepStreamEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RunStepStreamEvent other && Equals(other); + /// + public bool Equals(RunStepStreamEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.Serialization.cs index 59c11de06377..b9329fd5c499 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.Serialization.cs @@ -73,8 +73,8 @@ internal static RunStepToolCall DeserializeRunStepToolCall(JsonElement element, switch (discriminator.GetString()) { case "code_interpreter": return RunStepCodeInterpreterToolCall.DeserializeRunStepCodeInterpreterToolCall(element, options); + case "file_search": return RunStepFileSearchToolCall.DeserializeRunStepFileSearchToolCall(element, options); case "function": return RunStepFunctionToolCall.DeserializeRunStepFunctionToolCall(element, options); - case "retrieval": return RunStepRetrievalToolCall.DeserializeRunStepRetrievalToolCall(element, options); } } return UnknownRunStepToolCall.DeserializeUnknownRunStepToolCall(element, options); diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.cs index a1f39c74d40e..b458fd4827e9 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.cs @@ -13,7 +13,7 @@ namespace Azure.AI.OpenAI.Assistants /// /// An abstract representation of a detailed tool call as recorded within a run step for an existing run. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public abstract partial class RunStepToolCall { diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCallDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCallDetails.cs index dedd295f4d8a..1d55d40ac096 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCallDetails.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCallDetails.cs @@ -18,7 +18,7 @@ public partial class RunStepToolCallDetails : RunStepDetails /// /// A list of tool call details for this run step. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// /// is null. internal RunStepToolCallDetails(IEnumerable toolCalls) @@ -35,7 +35,7 @@ internal RunStepToolCallDetails(IEnumerable toolCalls) /// /// A list of tool call details for this run step. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// internal RunStepToolCallDetails(RunStepType type, IDictionary serializedAdditionalRawData, IReadOnlyList toolCalls) : base(type, serializedAdditionalRawData) { @@ -50,7 +50,7 @@ internal RunStepToolCallDetails() /// /// A list of tool call details for this run step. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IReadOnlyList ToolCalls { get; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStreamEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStreamEvent.cs new file mode 100644 index 000000000000..d9ce800c9594 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStreamEvent.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Run operation related streaming events. + public readonly partial struct RunStreamEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RunStreamEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadRunCreatedValue = "thread.run.created"; + private const string ThreadRunQueuedValue = "thread.run.queued"; + private const string ThreadRunInProgressValue = "thread.run.in_progress"; + private const string ThreadRunRequiresActionValue = "thread.run.requires_action"; + private const string ThreadRunCompletedValue = "thread.run.completed"; + private const string ThreadRunFailedValue = "thread.run.failed"; + private const string ThreadRunCancellingValue = "thread.run.cancelling"; + private const string ThreadRunCancelledValue = "thread.run.cancelled"; + private const string ThreadRunExpiredValue = "thread.run.expired"; + + /// Event sent when a new run is created. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunCreated { get; } = new RunStreamEvent(ThreadRunCreatedValue); + /// Event sent when a run moves to `queued` status. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunQueued { get; } = new RunStreamEvent(ThreadRunQueuedValue); + /// Event sent when a run moves to `in_progress` status. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunInProgress { get; } = new RunStreamEvent(ThreadRunInProgressValue); + /// Event sent when a run moves to `requires_action` status. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunRequiresAction { get; } = new RunStreamEvent(ThreadRunRequiresActionValue); + /// Event sent when a run is completed. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunCompleted { get; } = new RunStreamEvent(ThreadRunCompletedValue); + /// Event sent when a run fails. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunFailed { get; } = new RunStreamEvent(ThreadRunFailedValue); + /// Event sent when a run moves to `cancelling` status. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunCancelling { get; } = new RunStreamEvent(ThreadRunCancellingValue); + /// Event sent when a run is cancelled. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunCancelled { get; } = new RunStreamEvent(ThreadRunCancelledValue); + /// Event sent when a run is expired. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunExpired { get; } = new RunStreamEvent(ThreadRunExpiredValue); + /// Determines if two values are the same. + public static bool operator ==(RunStreamEvent left, RunStreamEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RunStreamEvent left, RunStreamEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator RunStreamEvent(string value) => new RunStreamEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RunStreamEvent other && Equals(other); + /// + public bool Equals(RunStreamEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.Serialization.cs index 142824a48025..c62ed0007517 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.Serialization.cs @@ -33,6 +33,18 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mode writer.WriteObjectValue(item, options); } writer.WriteEndArray(); + if (Optional.IsDefined(Stream)) + { + if (Stream != null) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(Stream.Value); + } + else + { + writer.WriteNull("stream"); + } + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -72,6 +84,7 @@ internal static SubmitToolOutputsToRunRequest DeserializeSubmitToolOutputsToRunR return null; } IReadOnlyList toolOutputs = default; + bool? stream = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -86,13 +99,23 @@ internal static SubmitToolOutputsToRunRequest DeserializeSubmitToolOutputsToRunR toolOutputs = array; continue; } + if (property.NameEquals("stream"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + stream = null; + continue; + } + stream = property.Value.GetBoolean(); + continue; + } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new SubmitToolOutputsToRunRequest(toolOutputs, serializedAdditionalRawData); + return new SubmitToolOutputsToRunRequest(toolOutputs, stream, serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.cs index 7fc21ab959a6..2971598450d1 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.cs @@ -47,7 +47,7 @@ internal partial class SubmitToolOutputsToRunRequest private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// The list of tool outputs requested by tool calls from the specified run. + /// A list of tools for which the outputs are being submitted. /// is null. internal SubmitToolOutputsToRunRequest(IEnumerable toolOutputs) { @@ -57,11 +57,13 @@ internal SubmitToolOutputsToRunRequest(IEnumerable toolOutputs) } /// Initializes a new instance of . - /// The list of tool outputs requested by tool calls from the specified run. + /// A list of tools for which the outputs are being submitted. + /// If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. /// Keeps track of any properties unknown to the library. - internal SubmitToolOutputsToRunRequest(IReadOnlyList toolOutputs, IDictionary serializedAdditionalRawData) + internal SubmitToolOutputsToRunRequest(IReadOnlyList toolOutputs, bool? stream, IDictionary serializedAdditionalRawData) { ToolOutputs = toolOutputs; + Stream = stream; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -70,7 +72,9 @@ internal SubmitToolOutputsToRunRequest() { } - /// The list of tool outputs requested by tool calls from the specified run. + /// A list of tools for which the outputs are being submitted. public IReadOnlyList ToolOutputs { get; } + /// If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + public bool? Stream { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.Serialization.cs index 940a42cf9293..da88c63f2836 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.Serialization.cs @@ -34,6 +34,35 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt writer.WriteNumberValue(CreatedAt, "U"); writer.WritePropertyName("thread_id"u8); writer.WriteStringValue(ThreadId); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + if (IncompleteDetails != null) + { + writer.WritePropertyName("incomplete_details"u8); + writer.WriteObjectValue(IncompleteDetails, options); + } + else + { + writer.WriteNull("incomplete_details"); + } + if (CompletedAt != null) + { + writer.WritePropertyName("completed_at"u8); + writer.WriteNumberValue(CompletedAt.Value, "U"); + } + else + { + writer.WriteNull("completed_at"); + } + if (IncompleteAt != null) + { + writer.WritePropertyName("incomplete_at"u8); + writer.WriteNumberValue(IncompleteAt.Value, "U"); + } + else + { + writer.WriteNull("incomplete_at"); + } writer.WritePropertyName("role"u8); writer.WriteStringValue(Role.ToString()); writer.WritePropertyName("content"u8); @@ -43,23 +72,38 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt writer.WriteObjectValue(item, options); } writer.WriteEndArray(); - if (Optional.IsDefined(AssistantId)) + if (AssistantId != null) { writer.WritePropertyName("assistant_id"u8); writer.WriteStringValue(AssistantId); } - if (Optional.IsDefined(RunId)) + else + { + writer.WriteNull("assistant_id"); + } + if (RunId != null) { writer.WritePropertyName("run_id"u8); writer.WriteStringValue(RunId); } - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) + else { - writer.WriteStringValue(item); + writer.WriteNull("run_id"); + } + if (Attachments != null && Optional.IsCollectionDefined(Attachments)) + { + writer.WritePropertyName("attachments"u8); + writer.WriteStartArray(); + foreach (var item in Attachments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("attachments"); } - writer.WriteEndArray(); if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -117,12 +161,16 @@ internal static ThreadMessage DeserializeThreadMessage(JsonElement element, Mode string @object = default; DateTimeOffset createdAt = default; string threadId = default; + MessageStatus status = default; + MessageIncompleteDetails incompleteDetails = default; + DateTimeOffset? completedAt = default; + DateTimeOffset? incompleteAt = default; MessageRole role = default; - IReadOnlyList content = default; + IList content = default; string assistantId = default; string runId = default; - IReadOnlyList fileIds = default; - IReadOnlyDictionary metadata = default; + IList attachments = default; + IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -147,6 +195,41 @@ internal static ThreadMessage DeserializeThreadMessage(JsonElement element, Mode threadId = property.Value.GetString(); continue; } + if (property.NameEquals("status"u8)) + { + status = new MessageStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("incomplete_details"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + incompleteDetails = null; + continue; + } + incompleteDetails = MessageIncompleteDetails.DeserializeMessageIncompleteDetails(property.Value, options); + continue; + } + if (property.NameEquals("completed_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + completedAt = null; + continue; + } + completedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("incomplete_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + incompleteAt = null; + continue; + } + incompleteAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } if (property.NameEquals("role"u8)) { role = new MessageRole(property.Value.GetString()); @@ -164,22 +247,37 @@ internal static ThreadMessage DeserializeThreadMessage(JsonElement element, Mode } if (property.NameEquals("assistant_id"u8)) { + if (property.Value.ValueKind == JsonValueKind.Null) + { + assistantId = null; + continue; + } assistantId = property.Value.GetString(); continue; } if (property.NameEquals("run_id"u8)) { + if (property.Value.ValueKind == JsonValueKind.Null) + { + runId = null; + continue; + } runId = property.Value.GetString(); continue; } - if (property.NameEquals("file_ids"u8)) + if (property.NameEquals("attachments"u8)) { - List array = new List(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + attachments = new ChangeTrackingList(); + continue; + } + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(item.GetString()); + array.Add(MessageAttachment.DeserializeMessageAttachment(item, options)); } - fileIds = array; + attachments = array; continue; } if (property.NameEquals("metadata"u8)) @@ -208,11 +306,15 @@ internal static ThreadMessage DeserializeThreadMessage(JsonElement element, Mode @object, createdAt, threadId, + status, + incompleteDetails, + completedAt, + incompleteAt, role, content, assistantId, runId, - fileIds, + attachments, metadata, serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.cs index 8bc5a7e7779b..c730b23b4dcf 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.cs @@ -50,31 +50,39 @@ public partial class ThreadMessage /// The identifier, which can be referenced in API endpoints. /// The Unix timestamp, in seconds, representing when this object was created. /// The ID of the thread that this message belongs to. + /// The status of the message. + /// On an incomplete message, details about why the message is incomplete. + /// The Unix timestamp (in seconds) for when the message was completed. + /// The Unix timestamp (in seconds) for when the message was marked as incomplete. /// The role associated with the assistant thread message. /// /// The list of content items associated with the assistant thread message. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. /// The available derived classes include and . /// - /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. - /// + /// If applicable, the ID of the assistant that authored this message. + /// If applicable, the ID of the run associated with the authoring of this message. + /// A list of files attached to the message, and the tools they were added to. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - /// , , or is null. - internal ThreadMessage(string id, DateTimeOffset createdAt, string threadId, MessageRole role, IEnumerable contentItems, IEnumerable fileIds, IReadOnlyDictionary metadata) + /// , or is null. + public ThreadMessage(string id, DateTimeOffset createdAt, string threadId, MessageStatus status, MessageIncompleteDetails incompleteDetails, DateTimeOffset? completedAt, DateTimeOffset? incompleteAt, MessageRole role, IEnumerable contentItems, string assistantId, string runId, IEnumerable attachments, IDictionary metadata) { Argument.AssertNotNull(id, nameof(id)); Argument.AssertNotNull(threadId, nameof(threadId)); Argument.AssertNotNull(contentItems, nameof(contentItems)); - Argument.AssertNotNull(fileIds, nameof(fileIds)); Id = id; CreatedAt = createdAt; ThreadId = threadId; + Status = status; + IncompleteDetails = incompleteDetails; + CompletedAt = completedAt; + IncompleteAt = incompleteAt; Role = role; ContentItems = contentItems.ToList(); - FileIds = fileIds.ToList(); + AssistantId = assistantId; + RunId = runId; + Attachments = attachments?.ToList(); Metadata = metadata; } @@ -83,6 +91,10 @@ internal ThreadMessage(string id, DateTimeOffset createdAt, string threadId, Mes /// The object type, which is always 'thread.message'. /// The Unix timestamp, in seconds, representing when this object was created. /// The ID of the thread that this message belongs to. + /// The status of the message. + /// On an incomplete message, details about why the message is incomplete. + /// The Unix timestamp (in seconds) for when the message was completed. + /// The Unix timestamp (in seconds) for when the message was marked as incomplete. /// The role associated with the assistant thread message. /// /// The list of content items associated with the assistant thread message. @@ -91,23 +103,24 @@ internal ThreadMessage(string id, DateTimeOffset createdAt, string threadId, Mes /// /// If applicable, the ID of the assistant that authored this message. /// If applicable, the ID of the run associated with the authoring of this message. - /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. - /// + /// A list of files attached to the message, and the tools they were added to. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal ThreadMessage(string id, string @object, DateTimeOffset createdAt, string threadId, MessageRole role, IReadOnlyList contentItems, string assistantId, string runId, IReadOnlyList fileIds, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal ThreadMessage(string id, string @object, DateTimeOffset createdAt, string threadId, MessageStatus status, MessageIncompleteDetails incompleteDetails, DateTimeOffset? completedAt, DateTimeOffset? incompleteAt, MessageRole role, IList contentItems, string assistantId, string runId, IList attachments, IDictionary metadata, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; CreatedAt = createdAt; ThreadId = threadId; + Status = status; + IncompleteDetails = incompleteDetails; + CompletedAt = completedAt; + IncompleteAt = incompleteAt; Role = role; ContentItems = contentItems; AssistantId = assistantId; RunId = runId; - FileIds = fileIds; + Attachments = attachments; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -118,30 +131,35 @@ internal ThreadMessage() } /// The identifier, which can be referenced in API endpoints. - public string Id { get; } + public string Id { get; set; } /// The Unix timestamp, in seconds, representing when this object was created. - public DateTimeOffset CreatedAt { get; } + public DateTimeOffset CreatedAt { get; set; } /// The ID of the thread that this message belongs to. - public string ThreadId { get; } + public string ThreadId { get; set; } + /// The status of the message. + public MessageStatus Status { get; set; } + /// On an incomplete message, details about why the message is incomplete. + public MessageIncompleteDetails IncompleteDetails { get; set; } + /// The Unix timestamp (in seconds) for when the message was completed. + public DateTimeOffset? CompletedAt { get; set; } + /// The Unix timestamp (in seconds) for when the message was marked as incomplete. + public DateTimeOffset? IncompleteAt { get; set; } /// The role associated with the assistant thread message. - public MessageRole Role { get; } + public MessageRole Role { get; set; } /// /// The list of content items associated with the assistant thread message. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. /// The available derived classes include and . /// - public IReadOnlyList ContentItems { get; } + public IList ContentItems { get; } /// If applicable, the ID of the assistant that authored this message. - public string AssistantId { get; } + public string AssistantId { get; set; } /// If applicable, the ID of the run associated with the authoring of this message. - public string RunId { get; } - /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. - /// - public IReadOnlyList FileIds { get; } + public string RunId { get; set; } + /// A list of files attached to the message, and the tools they were added to. + public IList Attachments { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - public IReadOnlyDictionary Metadata { get; } + public IDictionary Metadata { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.Serialization.cs similarity index 69% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.Serialization.cs index dd7625e2b011..7d6727044483 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.Serialization.cs @@ -13,16 +13,16 @@ namespace Azure.AI.OpenAI.Assistants { - internal partial class CreateMessageRequest : IUtf8JsonSerializable, IJsonModel + public partial class ThreadMessageOptions : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(CreateMessageRequest)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ThreadMessageOptions)} does not support writing '{format}' format."); } writer.WriteStartObject(); @@ -30,15 +30,22 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr writer.WriteStringValue(Role.ToString()); writer.WritePropertyName("content"u8); writer.WriteStringValue(Content); - if (Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(Attachments)) { - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) + if (Attachments != null) { - writer.WriteStringValue(item); + writer.WritePropertyName("attachments"u8); + writer.WriteStartArray(); + foreach (var item in Attachments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("attachments"); } - writer.WriteEndArray(); } if (Optional.IsCollectionDefined(Metadata)) { @@ -76,19 +83,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr writer.WriteEndObject(); } - CreateMessageRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ThreadMessageOptions 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(CreateMessageRequest)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ThreadMessageOptions)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateMessageRequest(document.RootElement, options); + return DeserializeThreadMessageOptions(document.RootElement, options); } - internal static CreateMessageRequest DeserializeCreateMessageRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static ThreadMessageOptions DeserializeThreadMessageOptions(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -98,8 +105,8 @@ internal static CreateMessageRequest DeserializeCreateMessageRequest(JsonElement } MessageRole role = default; string content = default; - IReadOnlyList fileIds = default; - IReadOnlyDictionary metadata = default; + IList attachments = default; + IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -114,18 +121,18 @@ internal static CreateMessageRequest DeserializeCreateMessageRequest(JsonElement content = property.Value.GetString(); continue; } - if (property.NameEquals("file_ids"u8)) + if (property.NameEquals("attachments"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(item.GetString()); + array.Add(MessageAttachment.DeserializeMessageAttachment(item, options)); } - fileIds = array; + attachments = array; continue; } if (property.NameEquals("metadata"u8)) @@ -148,46 +155,46 @@ internal static CreateMessageRequest DeserializeCreateMessageRequest(JsonElement } } serializedAdditionalRawData = rawDataDictionary; - return new CreateMessageRequest(role, content, fileIds ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new ThreadMessageOptions(role, content, attachments ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), 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(CreateMessageRequest)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ThreadMessageOptions)} does not support writing '{options.Format}' format."); } } - CreateMessageRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ThreadMessageOptions 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 DeserializeCreateMessageRequest(document.RootElement, options); + return DeserializeThreadMessageOptions(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(CreateMessageRequest)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ThreadMessageOptions)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static CreateMessageRequest FromResponse(Response response) + internal static ThreadMessageOptions FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeCreateMessageRequest(document.RootElement); + return DeserializeThreadMessageOptions(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.cs similarity index 53% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.cs index 5ce61588505d..6487c1ad7bf4 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.cs @@ -11,7 +11,7 @@ namespace Azure.AI.OpenAI.Assistants { /// A single message within an assistant thread, as provided during that thread's creation for its initial state. - public partial class ThreadInitializationMessage + public partial class ThreadMessageOptions { /// /// Keeps track of any properties unknown to the library. @@ -45,52 +45,70 @@ public partial class ThreadInitializationMessage /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - /// The role associated with the assistant thread message. Currently, only 'user' is supported when providing initial messages to a new thread. - /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via a separate call to the create message API. + /// Initializes a new instance of . + /// + /// The role of the entity that is creating the message. Allowed values include: + /// - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + /// - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into + /// the conversation. + /// + /// + /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via + /// a separate call to the create message API. + /// /// is null. - public ThreadInitializationMessage(MessageRole role, string content) + public ThreadMessageOptions(MessageRole role, string content) { Argument.AssertNotNull(content, nameof(content)); Role = role; Content = content; - FileIds = new ChangeTrackingList(); + Attachments = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } - /// Initializes a new instance of . - /// The role associated with the assistant thread message. Currently, only 'user' is supported when providing initial messages to a new thread. - /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via a separate call to the create message API. - /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. + /// Initializes a new instance of . + /// + /// The role of the entity that is creating the message. Allowed values include: + /// - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + /// - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into + /// the conversation. /// + /// + /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via + /// a separate call to the create message API. + /// + /// A list of files attached to the message, and the tools they should be added to. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal ThreadInitializationMessage(MessageRole role, string content, IList fileIds, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal ThreadMessageOptions(MessageRole role, string content, IList attachments, IDictionary metadata, IDictionary serializedAdditionalRawData) { Role = role; Content = content; - FileIds = fileIds; + Attachments = attachments; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal ThreadInitializationMessage() + /// Initializes a new instance of for deserialization. + internal ThreadMessageOptions() { } - /// The role associated with the assistant thread message. Currently, only 'user' is supported when providing initial messages to a new thread. + /// + /// The role of the entity that is creating the message. Allowed values include: + /// - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + /// - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into + /// the conversation. + /// public MessageRole Role { get; } - /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via a separate call to the create message API. - public string Content { get; } /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. + /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via + /// a separate call to the create message API. /// - public IList FileIds { get; } + public string Content { get; } + /// A list of files attached to the message, and the tools they should be added to. + public IList Attachments { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.Serialization.cs index e8b809e7542c..038592755098 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.Serialization.cs @@ -68,13 +68,6 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions writer.WriteObjectValue(item, options); } writer.WriteEndArray(); - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); if (ExpiresAt != null) @@ -122,6 +115,109 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions { writer.WriteNull("failed_at"); } + if (IncompleteDetails != null) + { + writer.WritePropertyName("incomplete_details"u8); + writer.WriteStringValue(IncompleteDetails.Value.ToString()); + } + else + { + writer.WriteNull("incomplete_details"); + } + if (Usage != null) + { + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + } + else + { + writer.WriteNull("usage"); + } + if (Optional.IsDefined(Temperature)) + { + if (Temperature != null) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + } + if (Optional.IsDefined(TopP)) + { + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + } + if (MaxPromptTokens != null) + { + writer.WritePropertyName("max_prompt_tokens"u8); + writer.WriteNumberValue(MaxPromptTokens.Value); + } + else + { + writer.WriteNull("max_prompt_tokens"); + } + if (MaxCompletionTokens != null) + { + writer.WritePropertyName("max_completion_tokens"u8); + writer.WriteNumberValue(MaxCompletionTokens.Value); + } + else + { + writer.WriteNull("max_completion_tokens"); + } + if (TruncationStrategy != null) + { + writer.WritePropertyName("truncation_strategy"u8); + writer.WriteObjectValue(TruncationStrategy, options); + } + else + { + writer.WriteNull("truncation_strategy"); + } + if (ToolChoice != null) + { + writer.WritePropertyName("tool_choice"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ToolChoice); +#else + using (JsonDocument document = JsonDocument.Parse(ToolChoice)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("tool_choice"); + } + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(ParallelToolCalls); + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); + } if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -185,13 +281,22 @@ internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderW string model = default; string instructions = default; IReadOnlyList tools = default; - IReadOnlyList fileIds = default; DateTimeOffset createdAt = default; DateTimeOffset? expiresAt = default; DateTimeOffset? startedAt = default; DateTimeOffset? completedAt = default; DateTimeOffset? cancelledAt = default; DateTimeOffset? failedAt = default; + IncompleteRunDetails? incompleteDetails = default; + RunCompletionUsage usage = default; + float? temperature = default; + float? topP = default; + int? maxPromptTokens = default; + int? maxCompletionTokens = default; + TruncationObject truncationStrategy = default; + BinaryData toolChoice = default; + bool parallelToolCalls = default; + BinaryData responseFormat = default; IReadOnlyDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -262,16 +367,6 @@ internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderW tools = array; continue; } - if (property.NameEquals("file_ids"u8)) - { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - fileIds = array; - continue; - } if (property.NameEquals("created_at"u8)) { createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); @@ -302,6 +397,101 @@ internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderW DeserializeNullableDateTimeOffset(property, ref failedAt); continue; } + if (property.NameEquals("incomplete_details"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + incompleteDetails = null; + continue; + } + incompleteDetails = new IncompleteRunDetails(property.Value.GetString()); + continue; + } + if (property.NameEquals("usage"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + usage = null; + continue; + } + usage = RunCompletionUsage.DeserializeRunCompletionUsage(property.Value, options); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("max_prompt_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxPromptTokens = null; + continue; + } + maxPromptTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_completion_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxCompletionTokens = null; + continue; + } + maxCompletionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("truncation_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + truncationStrategy = null; + continue; + } + truncationStrategy = TruncationObject.DeserializeTruncationObject(property.Value, options); + continue; + } + if (property.NameEquals("tool_choice"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolChoice = null; + continue; + } + toolChoice = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("parallel_tool_calls"u8)) + { + parallelToolCalls = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; + } + responseFormat = BinaryData.FromString(property.Value.GetRawText()); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -334,13 +524,22 @@ internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderW model, instructions, tools, - fileIds, createdAt, expiresAt, startedAt, completedAt, cancelledAt, failedAt, + incompleteDetails, + usage, + temperature, + topP, + maxPromptTokens, + maxCompletionTokens, + truncationStrategy, + toolChoice, + parallelToolCalls, + responseFormat, metadata, serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.cs index 31c97e45b559..16b96c0084e0 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.cs @@ -57,18 +57,25 @@ public partial class ThreadRun /// /// The overridden enabled tools used for this assistant thread run. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// - /// A list of attached file IDs, ordered by creation date in ascending order. /// The Unix timestamp, in seconds, representing when this object was created. /// The Unix timestamp, in seconds, representing when this item expires. /// The Unix timestamp, in seconds, representing when this item was started. /// The Unix timestamp, in seconds, representing when this completed. /// The Unix timestamp, in seconds, representing when this was cancelled. /// The Unix timestamp, in seconds, representing when this failed. + /// Details on why the run is incomplete. Will be `null` if the run is not incomplete. + /// Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + /// The maximum number of prompt tokens specified to have been used over the course of the run. + /// The maximum number of completion tokens specified to have been used over the course of the run. + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Whether to enable parallel function calling during tool use. + /// The response format of the tool calls used in this run. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - /// , , , , , or is null. - internal ThreadRun(string id, string threadId, string assistantId, RunStatus status, RunError lastError, string model, string instructions, IEnumerable tools, IEnumerable fileIds, DateTimeOffset createdAt, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, IReadOnlyDictionary metadata) + /// , , , , or is null. + internal ThreadRun(string id, string threadId, string assistantId, RunStatus status, RunError lastError, string model, string instructions, IEnumerable tools, DateTimeOffset createdAt, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, IncompleteRunDetails? incompleteDetails, RunCompletionUsage usage, int? maxPromptTokens, int? maxCompletionTokens, TruncationObject truncationStrategy, BinaryData toolChoice, bool parallelToolCalls, BinaryData responseFormat, IReadOnlyDictionary metadata) { Argument.AssertNotNull(id, nameof(id)); Argument.AssertNotNull(threadId, nameof(threadId)); @@ -76,7 +83,6 @@ internal ThreadRun(string id, string threadId, string assistantId, RunStatus sta Argument.AssertNotNull(model, nameof(model)); Argument.AssertNotNull(instructions, nameof(instructions)); Argument.AssertNotNull(tools, nameof(tools)); - Argument.AssertNotNull(fileIds, nameof(fileIds)); Id = id; ThreadId = threadId; @@ -86,13 +92,20 @@ internal ThreadRun(string id, string threadId, string assistantId, RunStatus sta Model = model; Instructions = instructions; Tools = tools.ToList(); - FileIds = fileIds.ToList(); CreatedAt = createdAt; ExpiresAt = expiresAt; StartedAt = startedAt; CompletedAt = completedAt; CancelledAt = cancelledAt; FailedAt = failedAt; + IncompleteDetails = incompleteDetails; + Usage = usage; + MaxPromptTokens = maxPromptTokens; + MaxCompletionTokens = maxCompletionTokens; + TruncationStrategy = truncationStrategy; + ToolChoice = toolChoice; + ParallelToolCalls = parallelToolCalls; + ResponseFormat = responseFormat; Metadata = metadata; } @@ -113,18 +126,27 @@ internal ThreadRun(string id, string threadId, string assistantId, RunStatus sta /// /// The overridden enabled tools used for this assistant thread run. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// - /// A list of attached file IDs, ordered by creation date in ascending order. /// The Unix timestamp, in seconds, representing when this object was created. /// The Unix timestamp, in seconds, representing when this item expires. /// The Unix timestamp, in seconds, representing when this item was started. /// The Unix timestamp, in seconds, representing when this completed. /// The Unix timestamp, in seconds, representing when this was cancelled. /// The Unix timestamp, in seconds, representing when this failed. + /// Details on why the run is incomplete. Will be `null` if the run is not incomplete. + /// Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + /// The sampling temperature used for this run. If not set, defaults to 1. + /// The nucleus sampling value used for this run. If not set, defaults to 1. + /// The maximum number of prompt tokens specified to have been used over the course of the run. + /// The maximum number of completion tokens specified to have been used over the course of the run. + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Whether to enable parallel function calling during tool use. + /// The response format of the tool calls used in this run. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal ThreadRun(string id, string @object, string threadId, string assistantId, RunStatus status, RequiredAction requiredAction, RunError lastError, string model, string instructions, IReadOnlyList tools, IReadOnlyList fileIds, DateTimeOffset createdAt, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal ThreadRun(string id, string @object, string threadId, string assistantId, RunStatus status, RequiredAction requiredAction, RunError lastError, string model, string instructions, IReadOnlyList tools, DateTimeOffset createdAt, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, IncompleteRunDetails? incompleteDetails, RunCompletionUsage usage, float? temperature, float? topP, int? maxPromptTokens, int? maxCompletionTokens, TruncationObject truncationStrategy, BinaryData toolChoice, bool parallelToolCalls, BinaryData responseFormat, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; @@ -136,13 +158,22 @@ internal ThreadRun(string id, string @object, string threadId, string assistantI Model = model; Instructions = instructions; Tools = tools; - FileIds = fileIds; CreatedAt = createdAt; ExpiresAt = expiresAt; StartedAt = startedAt; CompletedAt = completedAt; CancelledAt = cancelledAt; FailedAt = failedAt; + IncompleteDetails = incompleteDetails; + Usage = usage; + Temperature = temperature; + TopP = topP; + MaxPromptTokens = maxPromptTokens; + MaxCompletionTokens = maxCompletionTokens; + TruncationStrategy = truncationStrategy; + ToolChoice = toolChoice; + ParallelToolCalls = parallelToolCalls; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -176,11 +207,9 @@ internal ThreadRun() /// /// The overridden enabled tools used for this assistant thread run. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IReadOnlyList Tools { get; } - /// A list of attached file IDs, ordered by creation date in ascending order. - public IReadOnlyList FileIds { get; } /// The Unix timestamp, in seconds, representing when this object was created. public DateTimeOffset CreatedAt { get; } /// The Unix timestamp, in seconds, representing when this item expires. @@ -193,6 +222,112 @@ internal ThreadRun() public DateTimeOffset? CancelledAt { get; } /// The Unix timestamp, in seconds, representing when this failed. public DateTimeOffset? FailedAt { get; } + /// Details on why the run is incomplete. Will be `null` if the run is not incomplete. + public IncompleteRunDetails? IncompleteDetails { get; } + /// Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + public RunCompletionUsage Usage { get; } + /// The sampling temperature used for this run. If not set, defaults to 1. + public float? Temperature { get; } + /// The nucleus sampling value used for this run. If not set, defaults to 1. + public float? TopP { get; } + /// The maximum number of prompt tokens specified to have been used over the course of the run. + public int? MaxPromptTokens { get; } + /// The maximum number of completion tokens specified to have been used over the course of the run. + public int? MaxCompletionTokens { get; } + /// The strategy to use for dropping messages as the context windows moves forward. + public TruncationObject TruncationStrategy { get; } + /// + /// Controls whether or not and which tool is called by the model. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ToolChoice { get; } + /// Whether to enable parallel function calling during tool use. + public bool ParallelToolCalls { get; } + /// + /// The response format of the tool calls used in this run. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ResponseFormat { get; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IReadOnlyDictionary Metadata { get; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadStreamEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadStreamEvent.cs new file mode 100644 index 000000000000..172bd6c20d99 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadStreamEvent.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Thread operation related streaming events. + public readonly partial struct ThreadStreamEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ThreadStreamEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadCreatedValue = "thread.created"; + + /// Event sent when a new thread is created. The data of this event is of type AssistantThread. + public static ThreadStreamEvent ThreadCreated { get; } = new ThreadStreamEvent(ThreadCreatedValue); + /// Determines if two values are the same. + public static bool operator ==(ThreadStreamEvent left, ThreadStreamEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ThreadStreamEvent left, ThreadStreamEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ThreadStreamEvent(string value) => new ThreadStreamEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ThreadStreamEvent other && Equals(other); + /// + public bool Equals(ThreadStreamEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.Serialization.cs index e5bbd9e2b0cb..9ea0b740ff1a 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.Serialization.cs @@ -71,8 +71,8 @@ internal static ToolDefinition DeserializeToolDefinition(JsonElement element, Mo switch (discriminator.GetString()) { case "code_interpreter": return CodeInterpreterToolDefinition.DeserializeCodeInterpreterToolDefinition(element, options); + case "file_search": return FileSearchToolDefinition.DeserializeFileSearchToolDefinition(element, options); case "function": return FunctionToolDefinition.DeserializeFunctionToolDefinition(element, options); - case "retrieval": return RetrievalToolDefinition.DeserializeRetrievalToolDefinition(element, options); } } return UnknownToolDefinition.DeserializeUnknownToolDefinition(element, options); diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.cs index b9d063fe1c0c..be4c9b0d6cbf 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.cs @@ -13,7 +13,7 @@ namespace Azure.AI.OpenAI.Assistants /// /// An abstract representation of an input tool definition that an assistant can use. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public abstract partial class ToolDefinition { diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.Serialization.cs new file mode 100644 index 000000000000..044ce4d7c443 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.Serialization.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class ToolResources : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ToolResources)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(CodeInterpreter)) + { + writer.WritePropertyName("code_interpreter"u8); + writer.WriteObjectValue(CodeInterpreter, options); + } + if (Optional.IsDefined(FileSearch)) + { + writer.WritePropertyName("file_search"u8); + writer.WriteObjectValue(FileSearch, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ToolResources 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(ToolResources)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeToolResources(document.RootElement, options); + } + + internal static ToolResources DeserializeToolResources(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CodeInterpreterToolResource codeInterpreter = default; + FileSearchToolResource fileSearch = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code_interpreter"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + codeInterpreter = CodeInterpreterToolResource.DeserializeCodeInterpreterToolResource(property.Value, options); + continue; + } + if (property.NameEquals("file_search"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileSearch = FileSearchToolResource.DeserializeFileSearchToolResource(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData); + } + + 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(ToolResources)} does not support writing '{options.Format}' format."); + } + } + + ToolResources 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 DeserializeToolResources(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ToolResources)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ToolResources FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeToolResources(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.cs new file mode 100644 index 000000000000..408316763e48 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of + /// tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` + /// tool requires a list of vector store IDs. + /// + public partial class ToolResources + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ToolResources() + { + } + + /// Initializes a new instance of . + /// Resources to be used by the `code_interpreter tool` consisting of file IDs. + /// Resources to be used by the `file_search` tool consisting of vector store IDs. + /// Keeps track of any properties unknown to the library. + internal ToolResources(CodeInterpreterToolResource codeInterpreter, FileSearchToolResource fileSearch, IDictionary serializedAdditionalRawData) + { + CodeInterpreter = codeInterpreter; + FileSearch = fileSearch; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Resources to be used by the `code_interpreter tool` consisting of file IDs. + public CodeInterpreterToolResource CodeInterpreter { get; } + /// Resources to be used by the `file_search` tool consisting of vector store IDs. + public FileSearchToolResource FileSearch { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.Serialization.cs new file mode 100644 index 000000000000..d6f67e7b80e1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class TruncationObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(TruncationObject)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (Optional.IsDefined(LastMessages)) + { + if (LastMessages != null) + { + writer.WritePropertyName("last_messages"u8); + writer.WriteNumberValue(LastMessages.Value); + } + else + { + writer.WriteNull("last_messages"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + TruncationObject 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(TruncationObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTruncationObject(document.RootElement, options); + } + + internal static TruncationObject DeserializeTruncationObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + TruncationStrategy type = default; + int? lastMessages = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new TruncationStrategy(property.Value.GetString()); + continue; + } + if (property.NameEquals("last_messages"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + lastMessages = null; + continue; + } + lastMessages = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TruncationObject(type, lastMessages, serializedAdditionalRawData); + } + + 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(TruncationObject)} does not support writing '{options.Format}' format."); + } + } + + TruncationObject 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 DeserializeTruncationObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TruncationObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TruncationObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeTruncationObject(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.cs new file mode 100644 index 000000000000..a662e1b7761f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// Controls for how a thread will be truncated prior to the run. Use this to control the initial + /// context window of the run. + /// + public partial class TruncationObject + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will + /// be truncated to the `lastMessages` count most recent messages in the thread. When set to `auto`, messages in the middle of the thread + /// will be dropped to fit the context length of the model, `max_prompt_tokens`. + /// + public TruncationObject(TruncationStrategy type) + { + Type = type; + } + + /// Initializes a new instance of . + /// + /// The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will + /// be truncated to the `lastMessages` count most recent messages in the thread. When set to `auto`, messages in the middle of the thread + /// will be dropped to fit the context length of the model, `max_prompt_tokens`. + /// + /// The number of most recent messages from the thread when constructing the context for the run. + /// Keeps track of any properties unknown to the library. + internal TruncationObject(TruncationStrategy type, int? lastMessages, IDictionary serializedAdditionalRawData) + { + Type = type; + LastMessages = lastMessages; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TruncationObject() + { + } + + /// + /// The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will + /// be truncated to the `lastMessages` count most recent messages in the thread. When set to `auto`, messages in the middle of the thread + /// will be dropped to fit the context length of the model, `max_prompt_tokens`. + /// + public TruncationStrategy Type { get; set; } + /// The number of most recent messages from the thread when constructing the context for the run. + public int? LastMessages { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationStrategy.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationStrategy.cs new file mode 100644 index 000000000000..7e51ad3d3242 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationStrategy.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Possible truncation strategies for the thread. + public readonly partial struct TruncationStrategy : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public TruncationStrategy(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string LastMessagesValue = "last_messages"; + + /// Default value. Messages in the middle of the thread will be dropped to fit the context length of the model. + public static TruncationStrategy Auto { get; } = new TruncationStrategy(AutoValue); + /// The thread will truncate to the `lastMessages` count of recent messages. + public static TruncationStrategy LastMessages { get; } = new TruncationStrategy(LastMessagesValue); + /// Determines if two values are the same. + public static bool operator ==(TruncationStrategy left, TruncationStrategy right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(TruncationStrategy left, TruncationStrategy right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator TruncationStrategy(string value) => new TruncationStrategy(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is TruncationStrategy other && Equals(other); + /// + public bool Equals(TruncationStrategy other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.Serialization.cs new file mode 100644 index 000000000000..5a261b509b46 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownMessageDeltaContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaContent)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaContent 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(MessageDeltaContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaContent(document.RootElement, options); + } + + internal static UnknownMessageDeltaContent DeserializeUnknownMessageDeltaContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int index = default; + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownMessageDeltaContent(index, type, serializedAdditionalRawData); + } + + 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(MessageDeltaContent)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaContent 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 DeserializeMessageDeltaContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownMessageDeltaContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownMessageDeltaContent(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.cs new file mode 100644 index 000000000000..7b50c79a9122 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of MessageDeltaContent. + internal partial class UnknownMessageDeltaContent : MessageDeltaContent + { + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The type of content for this content part. + /// Keeps track of any properties unknown to the library. + internal UnknownMessageDeltaContent(int index, string type, IDictionary serializedAdditionalRawData) : base(index, type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownMessageDeltaContent() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.Serialization.cs new file mode 100644 index 000000000000..649bf2346f43 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownMessageDeltaTextAnnotation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MessageDeltaTextAnnotation)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MessageDeltaTextAnnotation 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(MessageDeltaTextAnnotation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextAnnotation(document.RootElement, options); + } + + internal static UnknownMessageDeltaTextAnnotation DeserializeUnknownMessageDeltaTextAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int index = default; + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownMessageDeltaTextAnnotation(index, type, serializedAdditionalRawData); + } + + 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(MessageDeltaTextAnnotation)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextAnnotation 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 DeserializeMessageDeltaTextAnnotation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextAnnotation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownMessageDeltaTextAnnotation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownMessageDeltaTextAnnotation(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.cs new file mode 100644 index 000000000000..3a65e8f866b4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of MessageDeltaTextAnnotation. + internal partial class UnknownMessageDeltaTextAnnotation : MessageDeltaTextAnnotation + { + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The type of the text content annotation. + /// Keeps track of any properties unknown to the library. + internal UnknownMessageDeltaTextAnnotation(int index, string type, IDictionary serializedAdditionalRawData) : base(index, type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownMessageDeltaTextAnnotation() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.Serialization.cs index f3ca2a8097cf..5c84db7d15dc 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.Serialization.cs @@ -30,10 +30,6 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW writer.WriteStringValue(Type); writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); - writer.WritePropertyName("start_index"u8); - writer.WriteNumberValue(StartIndex); - writer.WritePropertyName("end_index"u8); - writer.WriteNumberValue(EndIndex); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -74,8 +70,6 @@ internal static UnknownMessageTextAnnotation DeserializeUnknownMessageTextAnnota } string type = "Unknown"; string text = default; - int startIndex = default; - int endIndex = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -90,23 +84,13 @@ internal static UnknownMessageTextAnnotation DeserializeUnknownMessageTextAnnota text = property.Value.GetString(); continue; } - if (property.NameEquals("start_index"u8)) - { - startIndex = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("end_index"u8)) - { - endIndex = property.Value.GetInt32(); - continue; - } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new UnknownMessageTextAnnotation(type, text, startIndex, endIndex, serializedAdditionalRawData); + return new UnknownMessageTextAnnotation(type, text, serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.cs index 707b99138307..8df46b4ee1f3 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.cs @@ -16,10 +16,8 @@ internal partial class UnknownMessageTextAnnotation : MessageTextAnnotation /// Initializes a new instance of . /// The object type. /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// Keeps track of any properties unknown to the library. - internal UnknownMessageTextAnnotation(string type, string text, int startIndex, int endIndex, IDictionary serializedAdditionalRawData) : base(type, text, startIndex, endIndex, serializedAdditionalRawData) + internal UnknownMessageTextAnnotation(string type, string text, IDictionary serializedAdditionalRawData) : base(type, text, serializedAdditionalRawData) { } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.Serialization.cs new file mode 100644 index 000000000000..c7cdadff6c72 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownRunStepDeltaCodeInterpreterOutput : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaCodeInterpreterOutput)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaCodeInterpreterOutput 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(RunStepDeltaCodeInterpreterOutput)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterOutput(document.RootElement, options); + } + + internal static UnknownRunStepDeltaCodeInterpreterOutput DeserializeUnknownRunStepDeltaCodeInterpreterOutput(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int index = default; + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownRunStepDeltaCodeInterpreterOutput(index, type, serializedAdditionalRawData); + } + + 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(RunStepDeltaCodeInterpreterOutput)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterOutput 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 DeserializeRunStepDeltaCodeInterpreterOutput(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterOutput)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownRunStepDeltaCodeInterpreterOutput FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownRunStepDeltaCodeInterpreterOutput(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.cs new file mode 100644 index 000000000000..cda7227367bc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of RunStepDeltaCodeInterpreterOutput. + internal partial class UnknownRunStepDeltaCodeInterpreterOutput : RunStepDeltaCodeInterpreterOutput + { + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The type of the streaming run step tool call's Code Interpreter output. + /// Keeps track of any properties unknown to the library. + internal UnknownRunStepDeltaCodeInterpreterOutput(int index, string type, IDictionary serializedAdditionalRawData) : base(index, type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownRunStepDeltaCodeInterpreterOutput() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.Serialization.cs new file mode 100644 index 000000000000..5bad8ffd2844 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownRunStepDeltaDetail : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaDetail)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaDetail 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(RunStepDeltaDetail)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaDetail(document.RootElement, options); + } + + internal static UnknownRunStepDeltaDetail DeserializeUnknownRunStepDeltaDetail(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownRunStepDeltaDetail(type, serializedAdditionalRawData); + } + + 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(RunStepDeltaDetail)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaDetail 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 DeserializeRunStepDeltaDetail(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaDetail)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownRunStepDeltaDetail FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownRunStepDeltaDetail(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.cs new file mode 100644 index 000000000000..bf9efec7d936 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of RunStepDeltaDetail. + internal partial class UnknownRunStepDeltaDetail : RunStepDeltaDetail + { + /// Initializes a new instance of . + /// The object type for the run step detail object. + /// Keeps track of any properties unknown to the library. + internal UnknownRunStepDeltaDetail(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownRunStepDeltaDetail() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.Serialization.cs new file mode 100644 index 000000000000..a23cb38bcab1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownRunStepDeltaToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RunStepDeltaToolCall)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + RunStepDeltaToolCall 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(RunStepDeltaToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaToolCall(document.RootElement, options); + } + + internal static UnknownRunStepDeltaToolCall DeserializeUnknownRunStepDeltaToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int index = default; + string id = default; + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownRunStepDeltaToolCall(index, id, type, serializedAdditionalRawData); + } + + 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(RunStepDeltaToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaToolCall 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 DeserializeRunStepDeltaToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownRunStepDeltaToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownRunStepDeltaToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.cs new file mode 100644 index 000000000000..01e29a7c3518 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of RunStepDeltaToolCall. + internal partial class UnknownRunStepDeltaToolCall : RunStepDeltaToolCall + { + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// Keeps track of any properties unknown to the library. + internal UnknownRunStepDeltaToolCall(int index, string id, string type, IDictionary serializedAdditionalRawData) : base(index, id, type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownRunStepDeltaToolCall() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.Serialization.cs new file mode 100644 index 000000000000..a6bd403223af --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownVectorStoreChunkingStrategyRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreChunkingStrategyRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreChunkingStrategyRequest 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(VectorStoreChunkingStrategyRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreChunkingStrategyRequest(document.RootElement, options); + } + + internal static UnknownVectorStoreChunkingStrategyRequest DeserializeUnknownVectorStoreChunkingStrategyRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreChunkingStrategyRequestType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyRequestType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownVectorStoreChunkingStrategyRequest(type, serializedAdditionalRawData); + } + + 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(VectorStoreChunkingStrategyRequest)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreChunkingStrategyRequest 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 DeserializeVectorStoreChunkingStrategyRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownVectorStoreChunkingStrategyRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownVectorStoreChunkingStrategyRequest(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.cs new file mode 100644 index 000000000000..287e2c3a3496 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of VectorStoreChunkingStrategyRequest. + internal partial class UnknownVectorStoreChunkingStrategyRequest : VectorStoreChunkingStrategyRequest + { + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal UnknownVectorStoreChunkingStrategyRequest(VectorStoreChunkingStrategyRequestType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownVectorStoreChunkingStrategyRequest() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.Serialization.cs new file mode 100644 index 000000000000..1e409c04654c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownVectorStoreChunkingStrategyResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreChunkingStrategyResponse)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreChunkingStrategyResponse 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(VectorStoreChunkingStrategyResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreChunkingStrategyResponse(document.RootElement, options); + } + + internal static UnknownVectorStoreChunkingStrategyResponse DeserializeUnknownVectorStoreChunkingStrategyResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreChunkingStrategyResponseType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyResponseType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownVectorStoreChunkingStrategyResponse(type, serializedAdditionalRawData); + } + + 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(VectorStoreChunkingStrategyResponse)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreChunkingStrategyResponse 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 DeserializeVectorStoreChunkingStrategyResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownVectorStoreChunkingStrategyResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownVectorStoreChunkingStrategyResponse(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.cs new file mode 100644 index 000000000000..d81dc4925d3c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of VectorStoreChunkingStrategyResponse. + internal partial class UnknownVectorStoreChunkingStrategyResponse : VectorStoreChunkingStrategyResponse + { + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal UnknownVectorStoreChunkingStrategyResponse(VectorStoreChunkingStrategyResponseType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownVectorStoreChunkingStrategyResponse() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.Serialization.cs index c9b296e27af2..05de83029fa0 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.Serialization.cs @@ -77,15 +77,53 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReader } writer.WriteEndArray(); } - if (Optional.IsCollectionDefined(FileIds)) + if (Optional.IsDefined(ToolResources)) { - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + if (Optional.IsDefined(Temperature)) + { + if (Temperature != null) { - writer.WriteStringValue(item); + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + } + if (Optional.IsDefined(TopP)) + { + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + } + if (Optional.IsDefined(ResponseFormat)) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); } - writer.WriteEndArray(); } if (Optional.IsCollectionDefined(Metadata)) { @@ -148,7 +186,10 @@ internal static UpdateAssistantOptions DeserializeUpdateAssistantOptions(JsonEle string description = default; string instructions = default; IList tools = default; - IList fileIds = default; + UpdateToolResourcesOptions toolResources = default; + float? temperature = default; + float? topP = default; + BinaryData responseFormat = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -203,18 +244,43 @@ internal static UpdateAssistantOptions DeserializeUpdateAssistantOptions(JsonEle tools = array; continue; } - if (property.NameEquals("file_ids"u8)) + if (property.NameEquals("tool_resources"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + toolResources = UpdateToolResourcesOptions.DeserializeUpdateToolResourcesOptions(property.Value, options); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) { - array.Add(item.GetString()); + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; } - fileIds = array; + responseFormat = BinaryData.FromString(property.Value.GetRawText()); continue; } if (property.NameEquals("metadata"u8)) @@ -243,7 +309,10 @@ internal static UpdateAssistantOptions DeserializeUpdateAssistantOptions(JsonEle description, instructions, tools ?? new ChangeTrackingList(), - fileIds ?? new ChangeTrackingList(), + toolResources, + temperature, + topP, + responseFormat, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.cs index 85770c825c21..b3b50cb3bb79 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.cs @@ -49,7 +49,6 @@ public partial class UpdateAssistantOptions public UpdateAssistantOptions() { Tools = new ChangeTrackingList(); - FileIds = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } @@ -61,19 +60,36 @@ public UpdateAssistantOptions() /// /// The modified collection of tools to enable for the assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// - /// The modified list of previously uploaded fileIDs to attach to the assistant. + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, + /// the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// The response format of the tool calls used by this assistant. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal UpdateAssistantOptions(string model, string name, string description, string instructions, IList tools, IList fileIds, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal UpdateAssistantOptions(string model, string name, string description, string instructions, IList tools, UpdateToolResourcesOptions toolResources, float? temperature, float? topP, BinaryData responseFormat, IDictionary metadata, IDictionary serializedAdditionalRawData) { Model = model; Name = name; Description = description; Instructions = instructions; Tools = tools; - FileIds = fileIds; + ToolResources = toolResources; + Temperature = temperature; + TopP = topP; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -89,11 +105,71 @@ internal UpdateAssistantOptions(string model, string name, string description, s /// /// The modified collection of tools to enable for the assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IList Tools { get; } - /// The modified list of previously uploaded fileIDs to attach to the assistant. - public IList FileIds { get; } + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, + /// the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + public UpdateToolResourcesOptions ToolResources { get; set; } + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + public float? Temperature { get; set; } + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + public float? TopP { get; set; } + /// + /// The response format of the tool calls used by this assistant. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ResponseFormat { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.Serialization.cs similarity index 59% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.Serialization.cs index efb58bc378ae..d9faa3c9ac02 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.Serialization.cs @@ -13,19 +13,31 @@ namespace Azure.AI.OpenAI.Assistants { - internal partial class UpdateThreadRequest : IUtf8JsonSerializable, IJsonModel + public partial class UpdateAssistantThreadOptions : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(UpdateThreadRequest)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(UpdateAssistantThreadOptions)} does not support writing '{format}' format."); } writer.WriteStartObject(); + if (Optional.IsDefined(ToolResources)) + { + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } + } if (Optional.IsCollectionDefined(Metadata)) { if (Metadata != null) @@ -62,19 +74,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri writer.WriteEndObject(); } - UpdateThreadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + UpdateAssistantThreadOptions 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(UpdateThreadRequest)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(UpdateAssistantThreadOptions)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeUpdateThreadRequest(document.RootElement, options); + return DeserializeUpdateAssistantThreadOptions(document.RootElement, options); } - internal static UpdateThreadRequest DeserializeUpdateThreadRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static UpdateAssistantThreadOptions DeserializeUpdateAssistantThreadOptions(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -82,11 +94,22 @@ internal static UpdateThreadRequest DeserializeUpdateThreadRequest(JsonElement e { return null; } - IReadOnlyDictionary metadata = default; + UpdateToolResourcesOptions toolResources = default; + IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { + if (property.NameEquals("tool_resources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolResources = null; + continue; + } + toolResources = UpdateToolResourcesOptions.DeserializeUpdateToolResourcesOptions(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -107,46 +130,46 @@ internal static UpdateThreadRequest DeserializeUpdateThreadRequest(JsonElement e } } serializedAdditionalRawData = rawDataDictionary; - return new UpdateThreadRequest(metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new UpdateAssistantThreadOptions(toolResources, metadata ?? new ChangeTrackingDictionary(), 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(UpdateThreadRequest)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(UpdateAssistantThreadOptions)} does not support writing '{options.Format}' format."); } } - UpdateThreadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + UpdateAssistantThreadOptions 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 DeserializeUpdateThreadRequest(document.RootElement, options); + return DeserializeUpdateAssistantThreadOptions(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(UpdateThreadRequest)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(UpdateAssistantThreadOptions)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static UpdateThreadRequest FromResponse(Response response) + internal static UpdateAssistantThreadOptions FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeUpdateThreadRequest(document.RootElement); + return DeserializeUpdateAssistantThreadOptions(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.cs similarity index 53% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.cs index b58f5b245234..6b7141de049b 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.cs @@ -10,8 +10,8 @@ namespace Azure.AI.OpenAI.Assistants { - /// The CreateMessageRequest. - internal partial class CreateMessageRequest + /// The details used to update an existing assistant thread. + public partial class UpdateAssistantThreadOptions { /// /// Keeps track of any properties unknown to the library. @@ -45,47 +45,34 @@ internal partial class CreateMessageRequest /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - /// The role to associate with the new message. - /// The textual content for the new message. - /// is null. - internal CreateMessageRequest(MessageRole role, string content) + /// Initializes a new instance of . + public UpdateAssistantThreadOptions() { - Argument.AssertNotNull(content, nameof(content)); - - Role = role; - Content = content; - FileIds = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } - /// Initializes a new instance of . - /// The role to associate with the new message. - /// The textual content for the new message. - /// A list of up to 10 file IDs to associate with the message, as used by tools like 'code_interpreter' or 'retrieval' that can read files. + /// Initializes a new instance of . + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the + /// type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires + /// a list of vector store IDs + /// /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal CreateMessageRequest(MessageRole role, string content, IReadOnlyList fileIds, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal UpdateAssistantThreadOptions(UpdateToolResourcesOptions toolResources, IDictionary metadata, IDictionary serializedAdditionalRawData) { - Role = role; - Content = content; - FileIds = fileIds; + ToolResources = toolResources; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal CreateMessageRequest() - { - } - - /// The role to associate with the new message. - public MessageRole Role { get; } - /// The textual content for the new message. - public string Content { get; } - /// A list of up to 10 file IDs to associate with the message, as used by tools like 'code_interpreter' or 'retrieval' that can read files. - public IReadOnlyList FileIds { get; } + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the + /// type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires + /// a list of vector store IDs + /// + public UpdateToolResourcesOptions ToolResources { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - public IReadOnlyDictionary Metadata { get; } + public IDictionary Metadata { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.Serialization.cs new file mode 100644 index 000000000000..465ea22d89ba --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class UpdateCodeInterpreterToolResourceOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(UpdateCodeInterpreterToolResourceOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsCollectionDefined(FileIds)) + { + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + UpdateCodeInterpreterToolResourceOptions 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(UpdateCodeInterpreterToolResourceOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUpdateCodeInterpreterToolResourceOptions(document.RootElement, options); + } + + internal static UpdateCodeInterpreterToolResourceOptions DeserializeUpdateCodeInterpreterToolResourceOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList fileIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_ids"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + fileIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UpdateCodeInterpreterToolResourceOptions(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + 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(UpdateCodeInterpreterToolResourceOptions)} does not support writing '{options.Format}' format."); + } + } + + UpdateCodeInterpreterToolResourceOptions 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 DeserializeUpdateCodeInterpreterToolResourceOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UpdateCodeInterpreterToolResourceOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UpdateCodeInterpreterToolResourceOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUpdateCodeInterpreterToolResourceOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.cs new file mode 100644 index 000000000000..8c09267cd78d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Request object to update `code_interpreted` tool resources. + public partial class UpdateCodeInterpreterToolResourceOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public UpdateCodeInterpreterToolResourceOptions() + { + FileIds = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// A list of file IDs to override the current list of the assistant. + /// Keeps track of any properties unknown to the library. + internal UpdateCodeInterpreterToolResourceOptions(IList fileIds, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A list of file IDs to override the current list of the assistant. + public IList FileIds { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.Serialization.cs new file mode 100644 index 000000000000..8e5ab556eb60 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class UpdateFileSearchToolResourceOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(UpdateFileSearchToolResourceOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsCollectionDefined(VectorStoreIds)) + { + writer.WritePropertyName("vector_store_ids"u8); + writer.WriteStartArray(); + foreach (var item in VectorStoreIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + UpdateFileSearchToolResourceOptions 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(UpdateFileSearchToolResourceOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUpdateFileSearchToolResourceOptions(document.RootElement, options); + } + + internal static UpdateFileSearchToolResourceOptions DeserializeUpdateFileSearchToolResourceOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList vectorStoreIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("vector_store_ids"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorStoreIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UpdateFileSearchToolResourceOptions(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + 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(UpdateFileSearchToolResourceOptions)} does not support writing '{options.Format}' format."); + } + } + + UpdateFileSearchToolResourceOptions 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 DeserializeUpdateFileSearchToolResourceOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UpdateFileSearchToolResourceOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UpdateFileSearchToolResourceOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUpdateFileSearchToolResourceOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.cs new file mode 100644 index 000000000000..8742c5cd1b07 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Request object to update `file_search` tool resources. + public partial class UpdateFileSearchToolResourceOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public UpdateFileSearchToolResourceOptions() + { + VectorStoreIds = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// A list of vector store IDs to override the current list of the assistant. + /// Keeps track of any properties unknown to the library. + internal UpdateFileSearchToolResourceOptions(IList vectorStoreIds, IDictionary serializedAdditionalRawData) + { + VectorStoreIds = vectorStoreIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A list of vector store IDs to override the current list of the assistant. + public IList VectorStoreIds { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.Serialization.cs new file mode 100644 index 000000000000..38dbde3243f4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.Serialization.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class UpdateToolResourcesOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(UpdateToolResourcesOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(CodeInterpreter)) + { + writer.WritePropertyName("code_interpreter"u8); + writer.WriteObjectValue(CodeInterpreter, options); + } + if (Optional.IsDefined(FileSearch)) + { + writer.WritePropertyName("file_search"u8); + writer.WriteObjectValue(FileSearch, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + UpdateToolResourcesOptions 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(UpdateToolResourcesOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUpdateToolResourcesOptions(document.RootElement, options); + } + + internal static UpdateToolResourcesOptions DeserializeUpdateToolResourcesOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + UpdateCodeInterpreterToolResourceOptions codeInterpreter = default; + UpdateFileSearchToolResourceOptions fileSearch = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code_interpreter"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + codeInterpreter = UpdateCodeInterpreterToolResourceOptions.DeserializeUpdateCodeInterpreterToolResourceOptions(property.Value, options); + continue; + } + if (property.NameEquals("file_search"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileSearch = UpdateFileSearchToolResourceOptions.DeserializeUpdateFileSearchToolResourceOptions(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UpdateToolResourcesOptions(codeInterpreter, fileSearch, serializedAdditionalRawData); + } + + 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(UpdateToolResourcesOptions)} does not support writing '{options.Format}' format."); + } + } + + UpdateToolResourcesOptions 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 DeserializeUpdateToolResourcesOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UpdateToolResourcesOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UpdateToolResourcesOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUpdateToolResourcesOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.cs new file mode 100644 index 000000000000..919e93c57f1f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// Request object. A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. + /// For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of + /// vector store IDs. + /// + public partial class UpdateToolResourcesOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public UpdateToolResourcesOptions() + { + } + + /// Initializes a new instance of . + /// + /// Overrides the list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + /// Overrides the vector store attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + /// Keeps track of any properties unknown to the library. + internal UpdateToolResourcesOptions(UpdateCodeInterpreterToolResourceOptions codeInterpreter, UpdateFileSearchToolResourceOptions fileSearch, IDictionary serializedAdditionalRawData) + { + CodeInterpreter = codeInterpreter; + FileSearch = fileSearch; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// Overrides the list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + public UpdateCodeInterpreterToolResourceOptions CodeInterpreter { get; set; } + /// Overrides the vector store attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + public UpdateFileSearchToolResourceOptions FileSearch { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.Serialization.cs new file mode 100644 index 000000000000..131a35e56010 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.Serialization.cs @@ -0,0 +1,284 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStore : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStore)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + writer.WritePropertyName("usage_bytes"u8); + writer.WriteNumberValue(UsageBytes); + writer.WritePropertyName("file_counts"u8); + writer.WriteObjectValue(FileCounts, options); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + if (Optional.IsDefined(ExpiresAfter)) + { + writer.WritePropertyName("expires_after"u8); + writer.WriteObjectValue(ExpiresAfter, options); + } + if (Optional.IsDefined(ExpiresAt)) + { + if (ExpiresAt != null) + { + writer.WritePropertyName("expires_at"u8); + writer.WriteNumberValue(ExpiresAt.Value, "U"); + } + else + { + writer.WriteNull("expires_at"); + } + } + if (LastActiveAt != null) + { + writer.WritePropertyName("last_active_at"u8); + writer.WriteNumberValue(LastActiveAt.Value, "U"); + } + else + { + writer.WriteNull("last_active_at"); + } + if (Metadata != null && Optional.IsCollectionDefined(Metadata)) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + else + { + writer.WriteNull("metadata"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStore 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(VectorStore)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStore(document.RootElement, options); + } + + internal static VectorStore DeserializeVectorStore(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + VectorStoreObject @object = default; + DateTimeOffset createdAt = default; + string name = default; + int usageBytes = default; + VectorStoreFileCount fileCounts = default; + VectorStoreStatus status = default; + VectorStoreExpirationPolicy expiresAfter = default; + DateTimeOffset? expiresAt = default; + DateTimeOffset? lastActiveAt = default; + IReadOnlyDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new VectorStoreObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("usage_bytes"u8)) + { + usageBytes = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("file_counts"u8)) + { + fileCounts = VectorStoreFileCount.DeserializeVectorStoreFileCount(property.Value, options); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new VectorStoreStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("expires_after"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expiresAfter = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(property.Value, options); + continue; + } + if (property.NameEquals("expires_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + expiresAt = null; + continue; + } + expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("last_active_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + lastActiveAt = null; + continue; + } + lastActiveAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + metadata = new ChangeTrackingDictionary(); + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStore( + id, + @object, + createdAt, + name, + usageBytes, + fileCounts, + status, + expiresAfter, + expiresAt, + lastActiveAt, + metadata, + serializedAdditionalRawData); + } + + 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(VectorStore)} does not support writing '{options.Format}' format."); + } + } + + VectorStore 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 DeserializeVectorStore(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStore)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStore FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStore(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.cs new file mode 100644 index 000000000000..bd3231e10fc6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A vector store is a collection of processed files can be used by the `file_search` tool. + public partial class VectorStore + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the vector store was created. + /// The name of the vector store. + /// The total number of bytes used by the files in the vector store. + /// Files count grouped by status processed or being processed by this vector store. + /// The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + /// The Unix timestamp (in seconds) for when the vector store was last active. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// , or is null. + internal VectorStore(string id, DateTimeOffset createdAt, string name, int usageBytes, VectorStoreFileCount fileCounts, VectorStoreStatus status, DateTimeOffset? lastActiveAt, IReadOnlyDictionary metadata) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(name, nameof(name)); + Argument.AssertNotNull(fileCounts, nameof(fileCounts)); + + Id = id; + CreatedAt = createdAt; + Name = name; + UsageBytes = usageBytes; + FileCounts = fileCounts; + Status = status; + LastActiveAt = lastActiveAt; + Metadata = metadata; + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store`. + /// The Unix timestamp (in seconds) for when the vector store was created. + /// The name of the vector store. + /// The total number of bytes used by the files in the vector store. + /// Files count grouped by status processed or being processed by this vector store. + /// The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + /// Details on when this vector store expires. + /// The Unix timestamp (in seconds) for when the vector store will expire. + /// The Unix timestamp (in seconds) for when the vector store was last active. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Keeps track of any properties unknown to the library. + internal VectorStore(string id, VectorStoreObject @object, DateTimeOffset createdAt, string name, int usageBytes, VectorStoreFileCount fileCounts, VectorStoreStatus status, VectorStoreExpirationPolicy expiresAfter, DateTimeOffset? expiresAt, DateTimeOffset? lastActiveAt, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + { + Id = id; + Object = @object; + CreatedAt = createdAt; + Name = name; + UsageBytes = usageBytes; + FileCounts = fileCounts; + Status = status; + ExpiresAfter = expiresAfter; + ExpiresAt = expiresAt; + LastActiveAt = lastActiveAt; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStore() + { + } + + /// The identifier, which can be referenced in API endpoints. + public string Id { get; } + /// The object type, which is always `vector_store`. + public VectorStoreObject Object { get; } = VectorStoreObject.VectorStore; + + /// The Unix timestamp (in seconds) for when the vector store was created. + public DateTimeOffset CreatedAt { get; } + /// The name of the vector store. + public string Name { get; } + /// The total number of bytes used by the files in the vector store. + public int UsageBytes { get; } + /// Files count grouped by status processed or being processed by this vector store. + public VectorStoreFileCount FileCounts { get; } + /// The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + public VectorStoreStatus Status { get; } + /// Details on when this vector store expires. + public VectorStoreExpirationPolicy ExpiresAfter { get; } + /// The Unix timestamp (in seconds) for when the vector store will expire. + public DateTimeOffset? ExpiresAt { get; } + /// The Unix timestamp (in seconds) for when the vector store was last active. + public DateTimeOffset? LastActiveAt { get; } + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + public IReadOnlyDictionary Metadata { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.Serialization.cs new file mode 100644 index 000000000000..0502f7a71655 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreAutoChunkingStrategyRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreAutoChunkingStrategyRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreAutoChunkingStrategyRequest 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(VectorStoreAutoChunkingStrategyRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreAutoChunkingStrategyRequest(document.RootElement, options); + } + + internal static VectorStoreAutoChunkingStrategyRequest DeserializeVectorStoreAutoChunkingStrategyRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreChunkingStrategyRequestType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyRequestType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreAutoChunkingStrategyRequest(type, serializedAdditionalRawData); + } + + 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(VectorStoreAutoChunkingStrategyRequest)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreAutoChunkingStrategyRequest 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 DeserializeVectorStoreAutoChunkingStrategyRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreAutoChunkingStrategyRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new VectorStoreAutoChunkingStrategyRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreAutoChunkingStrategyRequest(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.cs new file mode 100644 index 000000000000..54ccde180223 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The default strategy. This strategy currently uses a max_chunk_size_tokens of 800 and chunk_overlap_tokens of 400. + public partial class VectorStoreAutoChunkingStrategyRequest : VectorStoreChunkingStrategyRequest + { + /// Initializes a new instance of . + public VectorStoreAutoChunkingStrategyRequest() + { + Type = VectorStoreChunkingStrategyRequestType.Auto; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal VectorStoreAutoChunkingStrategyRequest(VectorStoreChunkingStrategyRequestType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.Serialization.cs new file mode 100644 index 000000000000..b7858733008e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreAutoChunkingStrategyResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreAutoChunkingStrategyResponse)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreAutoChunkingStrategyResponse 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(VectorStoreAutoChunkingStrategyResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreAutoChunkingStrategyResponse(document.RootElement, options); + } + + internal static VectorStoreAutoChunkingStrategyResponse DeserializeVectorStoreAutoChunkingStrategyResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreChunkingStrategyResponseType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyResponseType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreAutoChunkingStrategyResponse(type, serializedAdditionalRawData); + } + + 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(VectorStoreAutoChunkingStrategyResponse)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreAutoChunkingStrategyResponse 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 DeserializeVectorStoreAutoChunkingStrategyResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreAutoChunkingStrategyResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new VectorStoreAutoChunkingStrategyResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreAutoChunkingStrategyResponse(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.cs new file mode 100644 index 000000000000..17218eca2365 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the chunking_strategy concept was introduced in the API. + public partial class VectorStoreAutoChunkingStrategyResponse : VectorStoreChunkingStrategyResponse + { + /// Initializes a new instance of . + internal VectorStoreAutoChunkingStrategyResponse() + { + Type = VectorStoreChunkingStrategyResponseType.Other; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal VectorStoreAutoChunkingStrategyResponse(VectorStoreChunkingStrategyResponseType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.Serialization.cs new file mode 100644 index 000000000000..74503df2a436 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.Serialization.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownVectorStoreChunkingStrategyRequest))] + public partial class VectorStoreChunkingStrategyRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreChunkingStrategyRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreChunkingStrategyRequest 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(VectorStoreChunkingStrategyRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreChunkingStrategyRequest(document.RootElement, options); + } + + internal static VectorStoreChunkingStrategyRequest DeserializeVectorStoreChunkingStrategyRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "auto": return VectorStoreAutoChunkingStrategyRequest.DeserializeVectorStoreAutoChunkingStrategyRequest(element, options); + case "static": return VectorStoreStaticChunkingStrategyRequest.DeserializeVectorStoreStaticChunkingStrategyRequest(element, options); + } + } + return UnknownVectorStoreChunkingStrategyRequest.DeserializeUnknownVectorStoreChunkingStrategyRequest(element, 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(VectorStoreChunkingStrategyRequest)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreChunkingStrategyRequest 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 DeserializeVectorStoreChunkingStrategyRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreChunkingStrategyRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreChunkingStrategyRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.cs new file mode 100644 index 000000000000..5f64bb63f131 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// An abstract representation of a vector store chunking strategy configuration. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class VectorStoreChunkingStrategyRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected VectorStoreChunkingStrategyRequest() + { + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal VectorStoreChunkingStrategyRequest(VectorStoreChunkingStrategyRequestType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type. + internal VectorStoreChunkingStrategyRequestType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequestType.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequestType.cs new file mode 100644 index 000000000000..1b9a9691c970 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequestType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Type of chunking strategy. + internal readonly partial struct VectorStoreChunkingStrategyRequestType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreChunkingStrategyRequestType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string StaticValue = "static"; + + /// auto. + public static VectorStoreChunkingStrategyRequestType Auto { get; } = new VectorStoreChunkingStrategyRequestType(AutoValue); + /// static. + public static VectorStoreChunkingStrategyRequestType Static { get; } = new VectorStoreChunkingStrategyRequestType(StaticValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreChunkingStrategyRequestType left, VectorStoreChunkingStrategyRequestType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreChunkingStrategyRequestType left, VectorStoreChunkingStrategyRequestType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreChunkingStrategyRequestType(string value) => new VectorStoreChunkingStrategyRequestType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreChunkingStrategyRequestType other && Equals(other); + /// + public bool Equals(VectorStoreChunkingStrategyRequestType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.Serialization.cs new file mode 100644 index 000000000000..49f33ceb5990 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.Serialization.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownVectorStoreChunkingStrategyResponse))] + public partial class VectorStoreChunkingStrategyResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreChunkingStrategyResponse)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreChunkingStrategyResponse 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(VectorStoreChunkingStrategyResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreChunkingStrategyResponse(document.RootElement, options); + } + + internal static VectorStoreChunkingStrategyResponse DeserializeVectorStoreChunkingStrategyResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "other": return VectorStoreAutoChunkingStrategyResponse.DeserializeVectorStoreAutoChunkingStrategyResponse(element, options); + case "static": return VectorStoreStaticChunkingStrategyResponse.DeserializeVectorStoreStaticChunkingStrategyResponse(element, options); + } + } + return UnknownVectorStoreChunkingStrategyResponse.DeserializeUnknownVectorStoreChunkingStrategyResponse(element, 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(VectorStoreChunkingStrategyResponse)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreChunkingStrategyResponse 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 DeserializeVectorStoreChunkingStrategyResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreChunkingStrategyResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreChunkingStrategyResponse(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.cs new file mode 100644 index 000000000000..a4e4bac4d2a8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// An abstract representation of a vector store chunking strategy configuration. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class VectorStoreChunkingStrategyResponse + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected VectorStoreChunkingStrategyResponse() + { + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal VectorStoreChunkingStrategyResponse(VectorStoreChunkingStrategyResponseType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type. + internal VectorStoreChunkingStrategyResponseType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponseType.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponseType.cs new file mode 100644 index 000000000000..8b4d6338955c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponseType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Type of chunking strategy. + internal readonly partial struct VectorStoreChunkingStrategyResponseType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreChunkingStrategyResponseType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string OtherValue = "other"; + private const string StaticValue = "static"; + + /// other. + public static VectorStoreChunkingStrategyResponseType Other { get; } = new VectorStoreChunkingStrategyResponseType(OtherValue); + /// static. + public static VectorStoreChunkingStrategyResponseType Static { get; } = new VectorStoreChunkingStrategyResponseType(StaticValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreChunkingStrategyResponseType left, VectorStoreChunkingStrategyResponseType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreChunkingStrategyResponseType left, VectorStoreChunkingStrategyResponseType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreChunkingStrategyResponseType(string value) => new VectorStoreChunkingStrategyResponseType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreChunkingStrategyResponseType other && Equals(other); + /// + public bool Equals(VectorStoreChunkingStrategyResponseType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.Serialization.cs similarity index 62% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.Serialization.cs index 10bfe96c2204..4e6da1fe0c1f 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.Serialization.cs @@ -13,16 +13,16 @@ namespace Azure.AI.OpenAI.Assistants { - internal partial class InternalAssistantFileDeletionStatus : IUtf8JsonSerializable, IJsonModel + public partial class VectorStoreDeletionStatus : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(InternalAssistantFileDeletionStatus)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(VectorStoreDeletionStatus)} does not support writing '{format}' format."); } writer.WriteStartObject(); @@ -50,19 +50,19 @@ void IJsonModel.Write(Utf8JsonWriter writer writer.WriteEndObject(); } - InternalAssistantFileDeletionStatus IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreDeletionStatus 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(InternalAssistantFileDeletionStatus)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(VectorStoreDeletionStatus)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAssistantFileDeletionStatus(document.RootElement, options); + return DeserializeVectorStoreDeletionStatus(document.RootElement, options); } - internal static InternalAssistantFileDeletionStatus DeserializeInternalAssistantFileDeletionStatus(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreDeletionStatus DeserializeVectorStoreDeletionStatus(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -72,7 +72,7 @@ internal static InternalAssistantFileDeletionStatus DeserializeInternalAssistant } string id = default; bool deleted = default; - InternalAssistantFileDeletionStatusObject @object = default; + VectorStoreDeletionStatusObject @object = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -89,7 +89,7 @@ internal static InternalAssistantFileDeletionStatus DeserializeInternalAssistant } if (property.NameEquals("object"u8)) { - @object = new InternalAssistantFileDeletionStatusObject(property.Value.GetString()); + @object = new VectorStoreDeletionStatusObject(property.Value.GetString()); continue; } if (options.Format != "W") @@ -98,46 +98,46 @@ internal static InternalAssistantFileDeletionStatus DeserializeInternalAssistant } } serializedAdditionalRawData = rawDataDictionary; - return new InternalAssistantFileDeletionStatus(id, deleted, @object, serializedAdditionalRawData); + return new VectorStoreDeletionStatus(id, deleted, @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(InternalAssistantFileDeletionStatus)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(VectorStoreDeletionStatus)} does not support writing '{options.Format}' format."); } } - InternalAssistantFileDeletionStatus IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + VectorStoreDeletionStatus 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 DeserializeInternalAssistantFileDeletionStatus(document.RootElement, options); + return DeserializeVectorStoreDeletionStatus(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalAssistantFileDeletionStatus)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(VectorStoreDeletionStatus)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static InternalAssistantFileDeletionStatus FromResponse(Response response) + internal static VectorStoreDeletionStatus FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAssistantFileDeletionStatus(document.RootElement); + return DeserializeVectorStoreDeletionStatus(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.cs similarity index 71% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.cs index 1a91eb299ceb..959f2da309e7 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.cs @@ -10,8 +10,8 @@ namespace Azure.AI.OpenAI.Assistants { - /// The status of an assistant file deletion operation. - internal partial class InternalAssistantFileDeletionStatus + /// Response object for deleting a vector store. + public partial class VectorStoreDeletionStatus { /// /// Keeps track of any properties unknown to the library. @@ -45,11 +45,11 @@ internal partial class InternalAssistantFileDeletionStatus /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The ID of the resource specified for deletion. /// A value indicating whether deletion was successful. /// is null. - internal InternalAssistantFileDeletionStatus(string id, bool deleted) + internal VectorStoreDeletionStatus(string id, bool deleted) { Argument.AssertNotNull(id, nameof(id)); @@ -57,12 +57,12 @@ internal InternalAssistantFileDeletionStatus(string id, bool deleted) Deleted = deleted; } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The ID of the resource specified for deletion. /// A value indicating whether deletion was successful. - /// The object type, which is always 'assistant.file.deleted'. + /// The object type, which is always 'vector_store.deleted'. /// Keeps track of any properties unknown to the library. - internal InternalAssistantFileDeletionStatus(string id, bool deleted, InternalAssistantFileDeletionStatusObject @object, IDictionary serializedAdditionalRawData) + internal VectorStoreDeletionStatus(string id, bool deleted, VectorStoreDeletionStatusObject @object, IDictionary serializedAdditionalRawData) { Id = id; Deleted = deleted; @@ -70,8 +70,8 @@ internal InternalAssistantFileDeletionStatus(string id, bool deleted, InternalAs _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal InternalAssistantFileDeletionStatus() + /// Initializes a new instance of for deserialization. + internal VectorStoreDeletionStatus() { } @@ -79,7 +79,7 @@ internal InternalAssistantFileDeletionStatus() public string Id { get; } /// A value indicating whether deletion was successful. public bool Deleted { get; } - /// The object type, which is always 'assistant.file.deleted'. - public InternalAssistantFileDeletionStatusObject Object { get; } = InternalAssistantFileDeletionStatusObject.AssistantFileDeleted; + /// The object type, which is always 'vector_store.deleted'. + public VectorStoreDeletionStatusObject Object { get; } = VectorStoreDeletionStatusObject.VectorStoreDeleted; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatusObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatusObject.cs new file mode 100644 index 000000000000..240b13fab2c5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatusObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The VectorStoreDeletionStatus_object. + public readonly partial struct VectorStoreDeletionStatusObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreDeletionStatusObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string VectorStoreDeletedValue = "vector_store.deleted"; + + /// vector_store.deleted. + public static VectorStoreDeletionStatusObject VectorStoreDeleted { get; } = new VectorStoreDeletionStatusObject(VectorStoreDeletedValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreDeletionStatusObject left, VectorStoreDeletionStatusObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreDeletionStatusObject left, VectorStoreDeletionStatusObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreDeletionStatusObject(string value) => new VectorStoreDeletionStatusObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreDeletionStatusObject other && Equals(other); + /// + public bool Equals(VectorStoreDeletionStatusObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.Serialization.cs new file mode 100644 index 000000000000..2b0f6fd8341f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreExpirationPolicy : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreExpirationPolicy)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("anchor"u8); + writer.WriteStringValue(Anchor.ToString()); + writer.WritePropertyName("days"u8); + writer.WriteNumberValue(Days); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreExpirationPolicy 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(VectorStoreExpirationPolicy)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreExpirationPolicy(document.RootElement, options); + } + + internal static VectorStoreExpirationPolicy DeserializeVectorStoreExpirationPolicy(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreExpirationPolicyAnchor anchor = default; + int days = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("anchor"u8)) + { + anchor = new VectorStoreExpirationPolicyAnchor(property.Value.GetString()); + continue; + } + if (property.NameEquals("days"u8)) + { + days = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreExpirationPolicy(anchor, days, serializedAdditionalRawData); + } + + 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(VectorStoreExpirationPolicy)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreExpirationPolicy 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 DeserializeVectorStoreExpirationPolicy(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreExpirationPolicy)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreExpirationPolicy FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreExpirationPolicy(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.cs new file mode 100644 index 000000000000..345d82299d9d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The expiration policy for a vector store. + public partial class VectorStoreExpirationPolicy + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`. + /// The anchor timestamp after which the expiration policy applies. + public VectorStoreExpirationPolicy(VectorStoreExpirationPolicyAnchor anchor, int days) + { + Anchor = anchor; + Days = days; + } + + /// Initializes a new instance of . + /// Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`. + /// The anchor timestamp after which the expiration policy applies. + /// Keeps track of any properties unknown to the library. + internal VectorStoreExpirationPolicy(VectorStoreExpirationPolicyAnchor anchor, int days, IDictionary serializedAdditionalRawData) + { + Anchor = anchor; + Days = days; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreExpirationPolicy() + { + } + + /// Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`. + public VectorStoreExpirationPolicyAnchor Anchor { get; set; } + /// The anchor timestamp after which the expiration policy applies. + public int Days { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicyAnchor.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicyAnchor.cs new file mode 100644 index 000000000000..864a769e6b50 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicyAnchor.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Describes the relationship between the days and the expiration of this vector store. + public readonly partial struct VectorStoreExpirationPolicyAnchor : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreExpirationPolicyAnchor(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string LastActiveAtValue = "last_active_at"; + + /// The expiration policy is based on the last time the vector store was active. + public static VectorStoreExpirationPolicyAnchor LastActiveAt { get; } = new VectorStoreExpirationPolicyAnchor(LastActiveAtValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreExpirationPolicyAnchor left, VectorStoreExpirationPolicyAnchor right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreExpirationPolicyAnchor left, VectorStoreExpirationPolicyAnchor right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreExpirationPolicyAnchor(string value) => new VectorStoreExpirationPolicyAnchor(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreExpirationPolicyAnchor other && Equals(other); + /// + public bool Equals(VectorStoreExpirationPolicyAnchor other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.Serialization.cs new file mode 100644 index 000000000000..c183395520a1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.Serialization.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreFile : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreFile)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("usage_bytes"u8); + writer.WriteNumberValue(UsageBytes); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("vector_store_id"u8); + writer.WriteStringValue(VectorStoreId); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + if (LastError != null) + { + writer.WritePropertyName("last_error"u8); + writer.WriteObjectValue(LastError, options); + } + else + { + writer.WriteNull("last_error"); + } + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreFile 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(VectorStoreFile)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreFile(document.RootElement, options); + } + + internal static VectorStoreFile DeserializeVectorStoreFile(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + VectorStoreFileObject @object = default; + int usageBytes = default; + DateTimeOffset createdAt = default; + string vectorStoreId = default; + VectorStoreFileStatus status = default; + VectorStoreFileError lastError = default; + VectorStoreChunkingStrategyResponse chunkingStrategy = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new VectorStoreFileObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("usage_bytes"u8)) + { + usageBytes = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("vector_store_id"u8)) + { + vectorStoreId = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new VectorStoreFileStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("last_error"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + lastError = null; + continue; + } + lastError = VectorStoreFileError.DeserializeVectorStoreFileError(property.Value, options); + continue; + } + if (property.NameEquals("chunking_strategy"u8)) + { + chunkingStrategy = VectorStoreChunkingStrategyResponse.DeserializeVectorStoreChunkingStrategyResponse(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreFile( + id, + @object, + usageBytes, + createdAt, + vectorStoreId, + status, + lastError, + chunkingStrategy, + serializedAdditionalRawData); + } + + 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(VectorStoreFile)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreFile 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 DeserializeVectorStoreFile(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreFile)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreFile FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreFile(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.cs new file mode 100644 index 000000000000..d7c12dbf07d8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.cs @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Description of a file attached to a vector store. + public partial class VectorStoreFile + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// + /// The total vector store usage in bytes. Note that this may be different from the original file + /// size. + /// + /// The Unix timestamp (in seconds) for when the vector store file was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + /// The last error associated with this vector store file. Will be `null` if there are no errors. + /// + /// The strategy used to chunk the file. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// , or is null. + internal VectorStoreFile(string id, int usageBytes, DateTimeOffset createdAt, string vectorStoreId, VectorStoreFileStatus status, VectorStoreFileError lastError, VectorStoreChunkingStrategyResponse chunkingStrategy) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(chunkingStrategy, nameof(chunkingStrategy)); + + Id = id; + UsageBytes = usageBytes; + CreatedAt = createdAt; + VectorStoreId = vectorStoreId; + Status = status; + LastError = lastError; + ChunkingStrategy = chunkingStrategy; + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store.file`. + /// + /// The total vector store usage in bytes. Note that this may be different from the original file + /// size. + /// + /// The Unix timestamp (in seconds) for when the vector store file was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + /// The last error associated with this vector store file. Will be `null` if there are no errors. + /// + /// The strategy used to chunk the file. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal VectorStoreFile(string id, VectorStoreFileObject @object, int usageBytes, DateTimeOffset createdAt, string vectorStoreId, VectorStoreFileStatus status, VectorStoreFileError lastError, VectorStoreChunkingStrategyResponse chunkingStrategy, IDictionary serializedAdditionalRawData) + { + Id = id; + Object = @object; + UsageBytes = usageBytes; + CreatedAt = createdAt; + VectorStoreId = vectorStoreId; + Status = status; + LastError = lastError; + ChunkingStrategy = chunkingStrategy; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreFile() + { + } + + /// The identifier, which can be referenced in API endpoints. + public string Id { get; } + /// The object type, which is always `vector_store.file`. + public VectorStoreFileObject Object { get; } = VectorStoreFileObject.VectorStoreFile; + + /// + /// The total vector store usage in bytes. Note that this may be different from the original file + /// size. + /// + public int UsageBytes { get; } + /// The Unix timestamp (in seconds) for when the vector store file was created. + public DateTimeOffset CreatedAt { get; } + /// The ID of the vector store that the file is attached to. + public string VectorStoreId { get; } + /// The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + public VectorStoreFileStatus Status { get; } + /// The last error associated with this vector store file. Will be `null` if there are no errors. + public VectorStoreFileError LastError { get; } + /// + /// The strategy used to chunk the file. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public VectorStoreChunkingStrategyResponse ChunkingStrategy { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.Serialization.cs new file mode 100644 index 000000000000..5b4b53d5a7b6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.Serialization.cs @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreFileBatch : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreFileBatch)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("vector_store_id"u8); + writer.WriteStringValue(VectorStoreId); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + writer.WritePropertyName("file_counts"u8); + writer.WriteObjectValue(FileCounts, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreFileBatch 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(VectorStoreFileBatch)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreFileBatch(document.RootElement, options); + } + + internal static VectorStoreFileBatch DeserializeVectorStoreFileBatch(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + VectorStoreFileBatchObject @object = default; + DateTimeOffset createdAt = default; + string vectorStoreId = default; + VectorStoreFileBatchStatus status = default; + VectorStoreFileCount fileCounts = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new VectorStoreFileBatchObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("vector_store_id"u8)) + { + vectorStoreId = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new VectorStoreFileBatchStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("file_counts"u8)) + { + fileCounts = VectorStoreFileCount.DeserializeVectorStoreFileCount(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreFileBatch( + id, + @object, + createdAt, + vectorStoreId, + status, + fileCounts, + serializedAdditionalRawData); + } + + 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(VectorStoreFileBatch)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreFileBatch 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 DeserializeVectorStoreFileBatch(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreFileBatch)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreFileBatch FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreFileBatch(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.cs new file mode 100644 index 000000000000..898dd2ab2b55 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A batch of files attached to a vector store. + public partial class VectorStoreFileBatch + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the vector store files batch was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + /// Files count grouped by status processed or being processed by this vector store. + /// , or is null. + internal VectorStoreFileBatch(string id, DateTimeOffset createdAt, string vectorStoreId, VectorStoreFileBatchStatus status, VectorStoreFileCount fileCounts) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(fileCounts, nameof(fileCounts)); + + Id = id; + CreatedAt = createdAt; + VectorStoreId = vectorStoreId; + Status = status; + FileCounts = fileCounts; + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store.file_batch`. + /// The Unix timestamp (in seconds) for when the vector store files batch was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + /// Files count grouped by status processed or being processed by this vector store. + /// Keeps track of any properties unknown to the library. + internal VectorStoreFileBatch(string id, VectorStoreFileBatchObject @object, DateTimeOffset createdAt, string vectorStoreId, VectorStoreFileBatchStatus status, VectorStoreFileCount fileCounts, IDictionary serializedAdditionalRawData) + { + Id = id; + Object = @object; + CreatedAt = createdAt; + VectorStoreId = vectorStoreId; + Status = status; + FileCounts = fileCounts; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreFileBatch() + { + } + + /// The identifier, which can be referenced in API endpoints. + public string Id { get; } + /// The object type, which is always `vector_store.file_batch`. + public VectorStoreFileBatchObject Object { get; } = VectorStoreFileBatchObject.VectorStoreFilesBatch; + + /// The Unix timestamp (in seconds) for when the vector store files batch was created. + public DateTimeOffset CreatedAt { get; } + /// The ID of the vector store that the file is attached to. + public string VectorStoreId { get; } + /// The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + public VectorStoreFileBatchStatus Status { get; } + /// Files count grouped by status processed or being processed by this vector store. + public VectorStoreFileCount FileCounts { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchObject.cs new file mode 100644 index 000000000000..ff607d482dfa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The VectorStoreFileBatch_object. + public readonly partial struct VectorStoreFileBatchObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileBatchObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string VectorStoreFilesBatchValue = "vector_store.files_batch"; + + /// vector_store.files_batch. + public static VectorStoreFileBatchObject VectorStoreFilesBatch { get; } = new VectorStoreFileBatchObject(VectorStoreFilesBatchValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileBatchObject left, VectorStoreFileBatchObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileBatchObject left, VectorStoreFileBatchObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileBatchObject(string value) => new VectorStoreFileBatchObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileBatchObject other && Equals(other); + /// + public bool Equals(VectorStoreFileBatchObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchStatus.cs new file mode 100644 index 000000000000..79d886ab6ccd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchStatus.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The status of the vector store file batch. + public readonly partial struct VectorStoreFileBatchStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileBatchStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InProgressValue = "in_progress"; + private const string CompletedValue = "completed"; + private const string CancelledValue = "cancelled"; + private const string FailedValue = "failed"; + + /// The vector store is still processing this file batch. + public static VectorStoreFileBatchStatus InProgress { get; } = new VectorStoreFileBatchStatus(InProgressValue); + /// the vector store file batch is ready for use. + public static VectorStoreFileBatchStatus Completed { get; } = new VectorStoreFileBatchStatus(CompletedValue); + /// The vector store file batch was cancelled. + public static VectorStoreFileBatchStatus Cancelled { get; } = new VectorStoreFileBatchStatus(CancelledValue); + /// The vector store file batch failed to process. + public static VectorStoreFileBatchStatus Failed { get; } = new VectorStoreFileBatchStatus(FailedValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileBatchStatus left, VectorStoreFileBatchStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileBatchStatus left, VectorStoreFileBatchStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileBatchStatus(string value) => new VectorStoreFileBatchStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileBatchStatus other && Equals(other); + /// + public bool Equals(VectorStoreFileBatchStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.Serialization.cs new file mode 100644 index 000000000000..e69faa13eec3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.Serialization.cs @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreFileCount : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreFileCount)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("in_progress"u8); + writer.WriteNumberValue(InProgress); + writer.WritePropertyName("completed"u8); + writer.WriteNumberValue(Completed); + writer.WritePropertyName("failed"u8); + writer.WriteNumberValue(Failed); + writer.WritePropertyName("cancelled"u8); + writer.WriteNumberValue(Cancelled); + writer.WritePropertyName("total"u8); + writer.WriteNumberValue(Total); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreFileCount 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(VectorStoreFileCount)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreFileCount(document.RootElement, options); + } + + internal static VectorStoreFileCount DeserializeVectorStoreFileCount(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int inProgress = default; + int completed = default; + int failed = default; + int cancelled = default; + int total = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("in_progress"u8)) + { + inProgress = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("completed"u8)) + { + completed = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("failed"u8)) + { + failed = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("cancelled"u8)) + { + cancelled = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("total"u8)) + { + total = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreFileCount( + inProgress, + completed, + failed, + cancelled, + total, + serializedAdditionalRawData); + } + + 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(VectorStoreFileCount)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreFileCount 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 DeserializeVectorStoreFileCount(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreFileCount)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreFileCount FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreFileCount(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.cs new file mode 100644 index 000000000000..a4fe9273bff4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Counts of files processed or being processed by this vector store grouped by status. + public partial class VectorStoreFileCount + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The number of files that are currently being processed. + /// The number of files that have been successfully processed. + /// The number of files that have failed to process. + /// The number of files that were cancelled. + /// The total number of files. + internal VectorStoreFileCount(int inProgress, int completed, int failed, int cancelled, int total) + { + InProgress = inProgress; + Completed = completed; + Failed = failed; + Cancelled = cancelled; + Total = total; + } + + /// Initializes a new instance of . + /// The number of files that are currently being processed. + /// The number of files that have been successfully processed. + /// The number of files that have failed to process. + /// The number of files that were cancelled. + /// The total number of files. + /// Keeps track of any properties unknown to the library. + internal VectorStoreFileCount(int inProgress, int completed, int failed, int cancelled, int total, IDictionary serializedAdditionalRawData) + { + InProgress = inProgress; + Completed = completed; + Failed = failed; + Cancelled = cancelled; + Total = total; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreFileCount() + { + } + + /// The number of files that are currently being processed. + public int InProgress { get; } + /// The number of files that have been successfully processed. + public int Completed { get; } + /// The number of files that have failed to process. + public int Failed { get; } + /// The number of files that were cancelled. + public int Cancelled { get; } + /// The total number of files. + public int Total { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.Serialization.cs new file mode 100644 index 000000000000..8ca0ff5dacf3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreFileDeletionStatus : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreFileDeletionStatus)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("deleted"u8); + writer.WriteBooleanValue(Deleted); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreFileDeletionStatus 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(VectorStoreFileDeletionStatus)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreFileDeletionStatus(document.RootElement, options); + } + + internal static VectorStoreFileDeletionStatus DeserializeVectorStoreFileDeletionStatus(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + bool deleted = default; + VectorStoreFileDeletionStatusObject @object = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("deleted"u8)) + { + deleted = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new VectorStoreFileDeletionStatusObject(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreFileDeletionStatus(id, deleted, @object, serializedAdditionalRawData); + } + + 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(VectorStoreFileDeletionStatus)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreFileDeletionStatus 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 DeserializeVectorStoreFileDeletionStatus(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreFileDeletionStatus)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreFileDeletionStatus FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreFileDeletionStatus(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.cs new file mode 100644 index 000000000000..009e5942a8ac --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Response object for deleting a vector store file relationship. + public partial class VectorStoreFileDeletionStatus + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// is null. + internal VectorStoreFileDeletionStatus(string id, bool deleted) + { + Argument.AssertNotNull(id, nameof(id)); + + Id = id; + Deleted = deleted; + } + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// The object type, which is always 'vector_store.deleted'. + /// Keeps track of any properties unknown to the library. + internal VectorStoreFileDeletionStatus(string id, bool deleted, VectorStoreFileDeletionStatusObject @object, IDictionary serializedAdditionalRawData) + { + Id = id; + Deleted = deleted; + Object = @object; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreFileDeletionStatus() + { + } + + /// The ID of the resource specified for deletion. + public string Id { get; } + /// A value indicating whether deletion was successful. + public bool Deleted { get; } + /// The object type, which is always 'vector_store.deleted'. + public VectorStoreFileDeletionStatusObject Object { get; } = VectorStoreFileDeletionStatusObject.VectorStoreFileDeleted; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatusObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatusObject.cs new file mode 100644 index 000000000000..ebd2a6f4d22f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatusObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The VectorStoreFileDeletionStatus_object. + public readonly partial struct VectorStoreFileDeletionStatusObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileDeletionStatusObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string VectorStoreFileDeletedValue = "vector_store.file.deleted"; + + /// vector_store.file.deleted. + public static VectorStoreFileDeletionStatusObject VectorStoreFileDeleted { get; } = new VectorStoreFileDeletionStatusObject(VectorStoreFileDeletedValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileDeletionStatusObject left, VectorStoreFileDeletionStatusObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileDeletionStatusObject left, VectorStoreFileDeletionStatusObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileDeletionStatusObject(string value) => new VectorStoreFileDeletionStatusObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileDeletionStatusObject other && Equals(other); + /// + public bool Equals(VectorStoreFileDeletionStatusObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.Serialization.cs new file mode 100644 index 000000000000..8473487e4562 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreFileError : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreFileError)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("code"u8); + writer.WriteStringValue(Code.ToString()); + writer.WritePropertyName("message"u8); + writer.WriteStringValue(Message); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreFileError 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(VectorStoreFileError)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreFileError(document.RootElement, options); + } + + internal static VectorStoreFileError DeserializeVectorStoreFileError(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreFileErrorCode code = default; + string message = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code"u8)) + { + code = new VectorStoreFileErrorCode(property.Value.GetString()); + continue; + } + if (property.NameEquals("message"u8)) + { + message = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreFileError(code, message, serializedAdditionalRawData); + } + + 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(VectorStoreFileError)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreFileError 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 DeserializeVectorStoreFileError(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreFileError)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreFileError FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreFileError(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResultsError.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.cs similarity index 50% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResultsError.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.cs index af8b8a13fe2a..5c96944e5f8e 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResultsError.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -5,10 +8,10 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI +namespace Azure.AI.OpenAI.Assistants { - /// The AzureContentFilterResultForPromptContentFilterResultsError. - internal partial class InternalAzureContentFilterResultForPromptContentFilterResultsError + /// Details on the error that may have ocurred while processing a file for this vector store. + public partial class VectorStoreFileError { /// /// Keeps track of any properties unknown to the library. @@ -40,12 +43,13 @@ internal partial class InternalAzureContentFilterResultForPromptContentFilterRes /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// A distinct, machine-readable code associated with the error. - /// A human-readable message associated with the error. + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// One of `server_error` or `rate_limit_exceeded`. + /// A human-readable description of the error. /// is null. - internal InternalAzureContentFilterResultForPromptContentFilterResultsError(int code, string message) + internal VectorStoreFileError(VectorStoreFileErrorCode code, string message) { Argument.AssertNotNull(message, nameof(message)); @@ -53,26 +57,25 @@ internal InternalAzureContentFilterResultForPromptContentFilterResultsError(int Message = message; } - /// Initializes a new instance of . - /// A distinct, machine-readable code associated with the error. - /// A human-readable message associated with the error. + /// Initializes a new instance of . + /// One of `server_error` or `rate_limit_exceeded`. + /// A human-readable description of the error. /// Keeps track of any properties unknown to the library. - internal InternalAzureContentFilterResultForPromptContentFilterResultsError(int code, string message, IDictionary serializedAdditionalRawData) + internal VectorStoreFileError(VectorStoreFileErrorCode code, string message, IDictionary serializedAdditionalRawData) { Code = code; Message = message; - SerializedAdditionalRawData = serializedAdditionalRawData; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal InternalAzureContentFilterResultForPromptContentFilterResultsError() + /// Initializes a new instance of for deserialization. + internal VectorStoreFileError() { } - /// A distinct, machine-readable code associated with the error. - internal int Code { get; set; } - /// A human-readable message associated with the error. - internal string Message { get; set; } + /// One of `server_error` or `rate_limit_exceeded`. + public VectorStoreFileErrorCode Code { get; } + /// A human-readable description of the error. + public string Message { get; } } } - diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileErrorCode.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileErrorCode.cs new file mode 100644 index 000000000000..ab280b4614cf --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileErrorCode.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Error code variants for vector store file processing. + public readonly partial struct VectorStoreFileErrorCode : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileErrorCode(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InternalErrorValue = "internal_error"; + private const string FileNotFoundValue = "file_not_found"; + private const string ParsingErrorValue = "parsing_error"; + private const string UnhandledMimeTypeValue = "unhandled_mime_type"; + + /// An internal error occurred. + public static VectorStoreFileErrorCode InternalError { get; } = new VectorStoreFileErrorCode(InternalErrorValue); + /// The file was not found. + public static VectorStoreFileErrorCode FileNotFound { get; } = new VectorStoreFileErrorCode(FileNotFoundValue); + /// The file could not be parsed. + public static VectorStoreFileErrorCode ParsingError { get; } = new VectorStoreFileErrorCode(ParsingErrorValue); + /// The file has an unhandled mime type. + public static VectorStoreFileErrorCode UnhandledMimeType { get; } = new VectorStoreFileErrorCode(UnhandledMimeTypeValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileErrorCode left, VectorStoreFileErrorCode right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileErrorCode left, VectorStoreFileErrorCode right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileErrorCode(string value) => new VectorStoreFileErrorCode(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileErrorCode other && Equals(other); + /// + public bool Equals(VectorStoreFileErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileObject.cs new file mode 100644 index 000000000000..f4d205e40ce2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The VectorStoreFile_object. + public readonly partial struct VectorStoreFileObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string VectorStoreFileValue = "vector_store.file"; + + /// vector_store.file. + public static VectorStoreFileObject VectorStoreFile { get; } = new VectorStoreFileObject(VectorStoreFileValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileObject left, VectorStoreFileObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileObject left, VectorStoreFileObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileObject(string value) => new VectorStoreFileObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileObject other && Equals(other); + /// + public bool Equals(VectorStoreFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatus.cs new file mode 100644 index 000000000000..62c5dc3711e8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatus.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Vector store file status. + public readonly partial struct VectorStoreFileStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InProgressValue = "in_progress"; + private const string CompletedValue = "completed"; + private const string FailedValue = "failed"; + private const string CancelledValue = "cancelled"; + + /// The file is currently being processed. + public static VectorStoreFileStatus InProgress { get; } = new VectorStoreFileStatus(InProgressValue); + /// The file has been successfully processed. + public static VectorStoreFileStatus Completed { get; } = new VectorStoreFileStatus(CompletedValue); + /// The file has failed to process. + public static VectorStoreFileStatus Failed { get; } = new VectorStoreFileStatus(FailedValue); + /// The file was cancelled. + public static VectorStoreFileStatus Cancelled { get; } = new VectorStoreFileStatus(CancelledValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileStatus left, VectorStoreFileStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileStatus left, VectorStoreFileStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileStatus(string value) => new VectorStoreFileStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileStatus other && Equals(other); + /// + public bool Equals(VectorStoreFileStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatusFilter.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatusFilter.cs new file mode 100644 index 000000000000..cd796f8cae2a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatusFilter.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Query parameter filter for vector store file retrieval endpoint. + public readonly partial struct VectorStoreFileStatusFilter : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileStatusFilter(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InProgressValue = "in_progress"; + private const string CompletedValue = "completed"; + private const string FailedValue = "failed"; + private const string CancelledValue = "cancelled"; + + /// Retrieve only files that are currently being processed. + public static VectorStoreFileStatusFilter InProgress { get; } = new VectorStoreFileStatusFilter(InProgressValue); + /// Retrieve only files that have been successfully processed. + public static VectorStoreFileStatusFilter Completed { get; } = new VectorStoreFileStatusFilter(CompletedValue); + /// Retrieve only files that have failed to process. + public static VectorStoreFileStatusFilter Failed { get; } = new VectorStoreFileStatusFilter(FailedValue); + /// Retrieve only files that were cancelled. + public static VectorStoreFileStatusFilter Cancelled { get; } = new VectorStoreFileStatusFilter(CancelledValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileStatusFilter left, VectorStoreFileStatusFilter right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileStatusFilter left, VectorStoreFileStatusFilter right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileStatusFilter(string value) => new VectorStoreFileStatusFilter(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileStatusFilter other && Equals(other); + /// + public bool Equals(VectorStoreFileStatusFilter other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreObject.cs new file mode 100644 index 000000000000..abbc8b915139 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The VectorStore_object. + public readonly partial struct VectorStoreObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string VectorStoreValue = "vector_store"; + + /// vector_store. + public static VectorStoreObject VectorStore { get; } = new VectorStoreObject(VectorStoreValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreObject left, VectorStoreObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreObject left, VectorStoreObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreObject(string value) => new VectorStoreObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreObject other && Equals(other); + /// + public bool Equals(VectorStoreObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.Serialization.cs new file mode 100644 index 000000000000..1d15eb029bc1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.Serialization.cs @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsCollectionDefined(FileIds)) + { + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (Optional.IsDefined(ExpiresAfter)) + { + writer.WritePropertyName("expires_after"u8); + writer.WriteObjectValue(ExpiresAfter, options); + } + if (Optional.IsDefined(ChunkingStrategy)) + { + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + } + if (Optional.IsCollectionDefined(Metadata)) + { + if (Metadata != null) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + else + { + writer.WriteNull("metadata"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreOptions 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(VectorStoreOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreOptions(document.RootElement, options); + } + + internal static VectorStoreOptions DeserializeVectorStoreOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList fileIds = default; + string name = default; + VectorStoreExpirationPolicy expiresAfter = default; + VectorStoreChunkingStrategyRequest chunkingStrategy = default; + IDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_ids"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + fileIds = array; + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("expires_after"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expiresAfter = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(property.Value, options); + continue; + } + if (property.NameEquals("chunking_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + chunkingStrategy = VectorStoreChunkingStrategyRequest.DeserializeVectorStoreChunkingStrategyRequest(property.Value, options); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreOptions( + fileIds ?? new ChangeTrackingList(), + name, + expiresAfter, + chunkingStrategy, + metadata ?? new ChangeTrackingDictionary(), + serializedAdditionalRawData); + } + + 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(VectorStoreOptions)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreOptions 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 DeserializeVectorStoreOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.cs new file mode 100644 index 000000000000..2aa8bd2f3858 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Request object for creating a vector store. + public partial class VectorStoreOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public VectorStoreOptions() + { + FileIds = new ChangeTrackingList(); + Metadata = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// A list of file IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// The name of the vector store. + /// Details on when this vector store expires. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. Only applicable if file_ids is non-empty. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Keeps track of any properties unknown to the library. + internal VectorStoreOptions(IList fileIds, string name, VectorStoreExpirationPolicy expiresAfter, VectorStoreChunkingStrategyRequest chunkingStrategy, IDictionary metadata, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + Name = name; + ExpiresAfter = expiresAfter; + ChunkingStrategy = chunkingStrategy; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A list of file IDs that the vector store should use. Useful for tools like `file_search` that can access files. + public IList FileIds { get; } + /// The name of the vector store. + public string Name { get; set; } + /// Details on when this vector store expires. + public VectorStoreExpirationPolicy ExpiresAfter { get; set; } + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. Only applicable if file_ids is non-empty. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public VectorStoreChunkingStrategyRequest ChunkingStrategy { get; set; } + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + public IDictionary Metadata { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.Serialization.cs new file mode 100644 index 000000000000..0b18f5655b55 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreStaticChunkingStrategyOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreStaticChunkingStrategyOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("max_chunk_size_tokens"u8); + writer.WriteNumberValue(MaxChunkSizeTokens); + writer.WritePropertyName("chunk_overlap_tokens"u8); + writer.WriteNumberValue(ChunkOverlapTokens); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreStaticChunkingStrategyOptions 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(VectorStoreStaticChunkingStrategyOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreStaticChunkingStrategyOptions(document.RootElement, options); + } + + internal static VectorStoreStaticChunkingStrategyOptions DeserializeVectorStoreStaticChunkingStrategyOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int maxChunkSizeTokens = default; + int chunkOverlapTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("max_chunk_size_tokens"u8)) + { + maxChunkSizeTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("chunk_overlap_tokens"u8)) + { + chunkOverlapTokens = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreStaticChunkingStrategyOptions(maxChunkSizeTokens, chunkOverlapTokens, serializedAdditionalRawData); + } + + 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(VectorStoreStaticChunkingStrategyOptions)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreStaticChunkingStrategyOptions 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 DeserializeVectorStoreStaticChunkingStrategyOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreStaticChunkingStrategyOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreStaticChunkingStrategyOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.cs new file mode 100644 index 000000000000..38db6670abf3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Options to configure a vector store static chunking strategy. + public partial class VectorStoreStaticChunkingStrategyOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The maximum number of tokens in each chunk. The default value is 800. The minimum value is 100 and the maximum value is 4096. + /// + /// The number of tokens that overlap between chunks. The default value is 400. + /// Note that the overlap must not exceed half of max_chunk_size_tokens. * + /// + public VectorStoreStaticChunkingStrategyOptions(int maxChunkSizeTokens, int chunkOverlapTokens) + { + MaxChunkSizeTokens = maxChunkSizeTokens; + ChunkOverlapTokens = chunkOverlapTokens; + } + + /// Initializes a new instance of . + /// The maximum number of tokens in each chunk. The default value is 800. The minimum value is 100 and the maximum value is 4096. + /// + /// The number of tokens that overlap between chunks. The default value is 400. + /// Note that the overlap must not exceed half of max_chunk_size_tokens. * + /// + /// Keeps track of any properties unknown to the library. + internal VectorStoreStaticChunkingStrategyOptions(int maxChunkSizeTokens, int chunkOverlapTokens, IDictionary serializedAdditionalRawData) + { + MaxChunkSizeTokens = maxChunkSizeTokens; + ChunkOverlapTokens = chunkOverlapTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreStaticChunkingStrategyOptions() + { + } + + /// The maximum number of tokens in each chunk. The default value is 800. The minimum value is 100 and the maximum value is 4096. + public int MaxChunkSizeTokens { get; set; } + /// + /// The number of tokens that overlap between chunks. The default value is 400. + /// Note that the overlap must not exceed half of max_chunk_size_tokens. * + /// + public int ChunkOverlapTokens { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.Serialization.cs new file mode 100644 index 000000000000..2d5098c57c0c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreStaticChunkingStrategyRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreStaticChunkingStrategyRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("static"u8); + writer.WriteObjectValue(Static, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreStaticChunkingStrategyRequest 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(VectorStoreStaticChunkingStrategyRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreStaticChunkingStrategyRequest(document.RootElement, options); + } + + internal static VectorStoreStaticChunkingStrategyRequest DeserializeVectorStoreStaticChunkingStrategyRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreStaticChunkingStrategyOptions @static = default; + VectorStoreChunkingStrategyRequestType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("static"u8)) + { + @static = VectorStoreStaticChunkingStrategyOptions.DeserializeVectorStoreStaticChunkingStrategyOptions(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyRequestType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreStaticChunkingStrategyRequest(type, serializedAdditionalRawData, @static); + } + + 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(VectorStoreStaticChunkingStrategyRequest)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreStaticChunkingStrategyRequest 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 DeserializeVectorStoreStaticChunkingStrategyRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new VectorStoreStaticChunkingStrategyRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreStaticChunkingStrategyRequest(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.cs new file mode 100644 index 000000000000..0a65da2962bd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A statically configured chunking strategy. + public partial class VectorStoreStaticChunkingStrategyRequest : VectorStoreChunkingStrategyRequest + { + /// Initializes a new instance of . + /// The options for the static chunking strategy. + /// is null. + public VectorStoreStaticChunkingStrategyRequest(VectorStoreStaticChunkingStrategyOptions @static) + { + Argument.AssertNotNull(@static, nameof(@static)); + + Type = VectorStoreChunkingStrategyRequestType.Static; + Static = @static; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + /// The options for the static chunking strategy. + internal VectorStoreStaticChunkingStrategyRequest(VectorStoreChunkingStrategyRequestType type, IDictionary serializedAdditionalRawData, VectorStoreStaticChunkingStrategyOptions @static) : base(type, serializedAdditionalRawData) + { + Static = @static; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreStaticChunkingStrategyRequest() + { + } + + /// The options for the static chunking strategy. + public VectorStoreStaticChunkingStrategyOptions Static { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.Serialization.cs new file mode 100644 index 000000000000..d478d4b4f14f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreStaticChunkingStrategyResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreStaticChunkingStrategyResponse)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("static"u8); + writer.WriteObjectValue(Static, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreStaticChunkingStrategyResponse 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(VectorStoreStaticChunkingStrategyResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreStaticChunkingStrategyResponse(document.RootElement, options); + } + + internal static VectorStoreStaticChunkingStrategyResponse DeserializeVectorStoreStaticChunkingStrategyResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreStaticChunkingStrategyOptions @static = default; + VectorStoreChunkingStrategyResponseType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("static"u8)) + { + @static = VectorStoreStaticChunkingStrategyOptions.DeserializeVectorStoreStaticChunkingStrategyOptions(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyResponseType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreStaticChunkingStrategyResponse(type, serializedAdditionalRawData, @static); + } + + 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(VectorStoreStaticChunkingStrategyResponse)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreStaticChunkingStrategyResponse 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 DeserializeVectorStoreStaticChunkingStrategyResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new VectorStoreStaticChunkingStrategyResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreStaticChunkingStrategyResponse(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.cs new file mode 100644 index 000000000000..5d2a0200bdcd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A statically configured chunking strategy. + public partial class VectorStoreStaticChunkingStrategyResponse : VectorStoreChunkingStrategyResponse + { + /// Initializes a new instance of . + /// The options for the static chunking strategy. + /// is null. + internal VectorStoreStaticChunkingStrategyResponse(VectorStoreStaticChunkingStrategyOptions @static) + { + Argument.AssertNotNull(@static, nameof(@static)); + + Type = VectorStoreChunkingStrategyResponseType.Static; + Static = @static; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + /// The options for the static chunking strategy. + internal VectorStoreStaticChunkingStrategyResponse(VectorStoreChunkingStrategyResponseType type, IDictionary serializedAdditionalRawData, VectorStoreStaticChunkingStrategyOptions @static) : base(type, serializedAdditionalRawData) + { + Static = @static; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreStaticChunkingStrategyResponse() + { + } + + /// The options for the static chunking strategy. + public VectorStoreStaticChunkingStrategyOptions Static { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStatus.cs new file mode 100644 index 000000000000..d8b1d0e87b45 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStatus.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Vector store possible status. + public readonly partial struct VectorStoreStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ExpiredValue = "expired"; + private const string InProgressValue = "in_progress"; + private const string CompletedValue = "completed"; + + /// expired status indicates that this vector store has expired and is no longer available for use. + public static VectorStoreStatus Expired { get; } = new VectorStoreStatus(ExpiredValue); + /// in_progress status indicates that this vector store is still processing files. + public static VectorStoreStatus InProgress { get; } = new VectorStoreStatus(InProgressValue); + /// completed status indicates that this vector store is ready for use. + public static VectorStoreStatus Completed { get; } = new VectorStoreStatus(CompletedValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreStatus left, VectorStoreStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreStatus left, VectorStoreStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreStatus(string value) => new VectorStoreStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreStatus other && Equals(other); + /// + public bool Equals(VectorStoreStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.Serialization.cs new file mode 100644 index 000000000000..1719c5abd919 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.Serialization.cs @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreUpdateOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(VectorStoreUpdateOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Name)) + { + if (Name != null) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + else + { + writer.WriteNull("name"); + } + } + if (Optional.IsDefined(ExpiresAfter)) + { + if (ExpiresAfter != null) + { + writer.WritePropertyName("expires_after"u8); + writer.WriteObjectValue(ExpiresAfter, options); + } + else + { + writer.WriteNull("expires_after"); + } + } + if (Optional.IsCollectionDefined(Metadata)) + { + if (Metadata != null) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + else + { + writer.WriteNull("metadata"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + VectorStoreUpdateOptions 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(VectorStoreUpdateOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreUpdateOptions(document.RootElement, options); + } + + internal static VectorStoreUpdateOptions DeserializeVectorStoreUpdateOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + VectorStoreExpirationPolicy expiresAfter = default; + IDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + name = null; + continue; + } + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("expires_after"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + expiresAfter = null; + continue; + } + expiresAfter = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(property.Value, options); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreUpdateOptions(name, expiresAfter, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + } + + 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(VectorStoreUpdateOptions)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreUpdateOptions 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 DeserializeVectorStoreUpdateOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreUpdateOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreUpdateOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeVectorStoreUpdateOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.cs similarity index 69% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.cs index 46ab2f35dbcb..e3bcef35dc48 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.cs @@ -10,8 +10,8 @@ namespace Azure.AI.OpenAI.Assistants { - /// The UpdateThreadRequest. - internal partial class UpdateThreadRequest + /// Request object for updating a vector store. + public partial class VectorStoreUpdateOptions { /// /// Keeps track of any properties unknown to the library. @@ -45,22 +45,30 @@ internal partial class UpdateThreadRequest /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - internal UpdateThreadRequest() + /// Initializes a new instance of . + public VectorStoreUpdateOptions() { Metadata = new ChangeTrackingDictionary(); } - /// Initializes a new instance of . + /// Initializes a new instance of . + /// The name of the vector store. + /// Details on when this vector store expires. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal UpdateThreadRequest(IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal VectorStoreUpdateOptions(string name, VectorStoreExpirationPolicy expiresAfter, IDictionary metadata, IDictionary serializedAdditionalRawData) { + Name = name; + ExpiresAfter = expiresAfter; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } + /// The name of the vector store. + public string Name { get; set; } + /// Details on when this vector store expires. + public VectorStoreExpirationPolicy ExpiresAfter { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - public IReadOnlyDictionary Metadata { get; } + public IDictionary Metadata { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/tsp-location.yaml b/sdk/openai/Azure.AI.OpenAI.Assistants/tsp-location.yaml index 58f812caec89..2c62d8730936 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/tsp-location.yaml +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/tsp-location.yaml @@ -1,3 +1,4 @@ directory: specification/ai/OpenAI.Assistants -commit: 4fef3a8d819f8fc8eef6a3b68320f710e666b72a +commit: cc338f96a11ef2749b5cdf4a1ec0b69208763cc9 repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIClientBuilderExtensions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIClientBuilderExtensions.cs new file mode 100644 index 000000000000..bc32a7f2b1a4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIClientBuilderExtensions.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure; +using Azure.AI.OpenAI; +using Azure.Core.Extensions; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class AIOpenAIClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + /// A credential used to authenticate to an Azure Service. + public static IAzureClientBuilder AddOpenAIClient(this TBuilder builder, Uri endpoint, AzureKeyCredential credential) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new OpenAIClient(endpoint, credential, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + public static IAzureClientBuilder AddOpenAIClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new OpenAIClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddOpenAIClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIModelFactory.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIModelFactory.cs new file mode 100644 index 000000000000..3cdccf77ca30 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIModelFactory.cs @@ -0,0 +1,1499 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Model factory for models. + public static partial class AIOpenAIModelFactory + { + /// Initializes a new instance of . + /// + /// The audio data to transcribe. This must be the binary content of a file in one of the supported media formats: + /// flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm. + /// + /// The optional filename or descriptive identifier to associate with with the audio data. + /// The requested format of the transcription response data, which will influence the content and detail of the result. + /// + /// The primary spoken language of the audio data to be transcribed, supplied as a two-letter ISO-639-1 language code + /// such as 'en' or 'fr'. + /// Providing this known input language is optional but may improve the accuracy and/or latency of transcription. + /// + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + /// + /// The sampling temperature, between 0 and 1. + /// Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + /// If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit. + /// + /// + /// The timestamp granularities to populate for this transcription. + /// `response_format` must be set `verbose_json` to use timestamp granularities. + /// Either or both of these options are supported: `word`, or `segment`. + /// Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. + /// + /// The model to use for this transcription request. + /// A new instance for mocking. + public static AudioTranscriptionOptions AudioTranscriptionOptions(Stream audioData = null, string filename = null, AudioTranscriptionFormat? responseFormat = null, string language = null, string prompt = null, float? temperature = null, IEnumerable timestampGranularities = null, string deploymentName = null) + { + timestampGranularities ??= new List(); + + return new AudioTranscriptionOptions( + audioData, + filename, + responseFormat, + language, + prompt, + temperature, + timestampGranularities?.ToList(), + deploymentName, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The 0-based index of this segment within a transcription. + /// The time at which this segment started relative to the beginning of the transcribed audio. + /// The time at which this segment ended relative to the beginning of the transcribed audio. + /// The transcribed text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the transcribed text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// A new instance for mocking. + public static AudioTranscriptionSegment AudioTranscriptionSegment(int id = default, TimeSpan start = default, TimeSpan end = default, string text = null, float temperature = default, float averageLogProbability = default, float compressionRatio = default, float noSpeechProbability = default, IEnumerable tokens = null, int seek = default) + { + tokens ??= new List(); + + return new AudioTranscriptionSegment( + id, + start, + end, + text, + temperature, + averageLogProbability, + compressionRatio, + noSpeechProbability, + tokens?.ToList(), + seek, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The textual content of the word. + /// The start time of the word relative to the beginning of the audio, expressed in seconds. + /// The end time of the word relative to the beginning of the audio, expressed in seconds. + /// A new instance for mocking. + public static AudioTranscriptionWord AudioTranscriptionWord(string word = null, TimeSpan start = default, TimeSpan end = default) + { + return new AudioTranscriptionWord(word, start, end, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The audio data to translate. This must be the binary content of a file in one of the supported media formats: + /// flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm. + /// + /// The optional filename or descriptive identifier to associate with with the audio data. + /// The requested format of the translation response data, which will influence the content and detail of the result. + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + /// + /// The sampling temperature, between 0 and 1. + /// Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + /// If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit. + /// + /// The model to use for this translation request. + /// A new instance for mocking. + public static AudioTranslationOptions AudioTranslationOptions(Stream audioData = null, string filename = null, AudioTranslationFormat? responseFormat = null, string prompt = null, float? temperature = null, string deploymentName = null) + { + return new AudioTranslationOptions( + audioData, + filename, + responseFormat, + prompt, + temperature, + deploymentName, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The 0-based index of this segment within a translation. + /// The time at which this segment started relative to the beginning of the translated audio. + /// The time at which this segment ended relative to the beginning of the translated audio. + /// The translated text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the translated text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// A new instance for mocking. + public static AudioTranslationSegment AudioTranslationSegment(int id = default, TimeSpan start = default, TimeSpan end = default, string text = null, float temperature = default, float averageLogProbability = default, float compressionRatio = default, float noSpeechProbability = default, IEnumerable tokens = null, int seek = default) + { + tokens ??= new List(); + + return new AudioTranslationSegment( + id, + start, + end, + text, + temperature, + averageLogProbability, + compressionRatio, + noSpeechProbability, + tokens?.ToList(), + seek, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A unique identifier associated with this completions response. + /// + /// The first timestamp associated with generation activity for this completions response, + /// represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. + /// + /// + /// Content filtering results for zero or more prompts in the request. In a streaming request, + /// results for different prompts may arrive at different times or in different orders. + /// + /// + /// The collection of completions choices associated with this completions response. + /// Generally, `n` choices are generated per provided prompt with a default value of 1. + /// Token limits and other settings may limit the number of choices generated. + /// + /// Usage information for tokens processed and generated as part of this completions operation. + /// + /// This fingerprint represents the backend configuration that the model runs with. + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + /// + /// A new instance for mocking. + public static Completions Completions(string id = null, DateTimeOffset created = default, IEnumerable promptFilterResults = null, IEnumerable choices = null, CompletionsUsage usage = null, string systemFingerprint = null) + { + promptFilterResults ??= new List(); + choices ??= new List(); + + return new Completions( + id, + created, + promptFilterResults?.ToList(), + choices?.ToList(), + usage, + systemFingerprint, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of this prompt in the set of prompt results. + /// Content filtering results for this prompt. + /// A new instance for mocking. + public static ContentFilterResultsForPrompt ContentFilterResultsForPrompt(int promptIndex = default, ContentFilterResultDetailsForPrompt contentFilterResults = null) + { + return new ContentFilterResultsForPrompt(promptIndex, contentFilterResults, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Describes detection results against configured custom blocklists. + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + /// Whether a jailbreak attempt was detected in the prompt. + /// Whether an indirect attack was detected in the prompt. + /// A new instance for mocking. + public static ContentFilterResultDetailsForPrompt ContentFilterResultDetailsForPrompt(ContentFilterResult sexual = null, ContentFilterResult violence = null, ContentFilterResult hate = null, ContentFilterResult selfHarm = null, ContentFilterDetectionResult profanity = null, ContentFilterDetailedResults customBlocklists = null, ResponseError error = null, ContentFilterDetectionResult jailbreak = null, ContentFilterDetectionResult indirectAttack = null) + { + return new ContentFilterResultDetailsForPrompt( + sexual, + violence, + hate, + selfHarm, + profanity, + customBlocklists, + error, + jailbreak, + indirectAttack, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// Ratings for the intensity and risk level of filtered content. + /// A new instance for mocking. + public static ContentFilterResult ContentFilterResult(bool filtered = default, ContentFilterSeverity severity = default) + { + return new ContentFilterResult(filtered, severity, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + /// A new instance for mocking. + public static ContentFilterDetectionResult ContentFilterDetectionResult(bool filtered = default, bool detected = default) + { + return new ContentFilterDetectionResult(filtered, detected, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// The collection of detailed blocklist result information. + /// A new instance for mocking. + public static ContentFilterDetailedResults ContentFilterDetailedResults(bool filtered = default, IEnumerable details = null) + { + details ??= new List(); + + return new ContentFilterDetailedResults(filtered, details?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// The ID of the custom blocklist evaluated. + /// A new instance for mocking. + public static ContentFilterBlocklistIdResult ContentFilterBlocklistIdResult(bool filtered = default, string id = null) + { + return new ContentFilterBlocklistIdResult(filtered, id, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The generated text for a given completions prompt. + /// The ordered index associated with this completions choice. + /// + /// Information about the content filtering category (hate, sexual, violence, self_harm), if it + /// has been detected, as well as the severity level (very_low, low, medium, high-scale that + /// determines the intensity and risk level of harmful content) and if it has been filtered or not. + /// + /// The log probabilities model for tokens associated with this completions choice. + /// Reason for finishing. + /// A new instance for mocking. + public static Choice Choice(string text = null, int index = default, ContentFilterResultsForChoice contentFilterResults = null, CompletionsLogProbabilityModel logProbabilityModel = null, CompletionsFinishReason? finishReason = null) + { + return new Choice( + text, + index, + contentFilterResults, + logProbabilityModel, + finishReason, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Describes detection results against configured custom blocklists. + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + /// Information about detection of protected text material. + /// Information about detection of protected code material. + /// A new instance for mocking. + public static ContentFilterResultsForChoice ContentFilterResultsForChoice(ContentFilterResult sexual = null, ContentFilterResult violence = null, ContentFilterResult hate = null, ContentFilterResult selfHarm = null, ContentFilterDetectionResult profanity = null, ContentFilterDetailedResults customBlocklists = null, ResponseError error = null, ContentFilterDetectionResult protectedMaterialText = null, ContentFilterCitedDetectionResult protectedMaterialCode = null) + { + return new ContentFilterResultsForChoice( + sexual, + violence, + hate, + selfHarm, + profanity, + customBlocklists, + error, + protectedMaterialText, + protectedMaterialCode, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + /// The internet location associated with the detection. + /// The license description associated with the detection. + /// A new instance for mocking. + public static ContentFilterCitedDetectionResult ContentFilterCitedDetectionResult(bool filtered = default, bool detected = default, Uri url = null, string license = null) + { + return new ContentFilterCitedDetectionResult(filtered, detected, url, license, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The textual forms of tokens evaluated in this probability model. + /// A collection of log probability values for the tokens in this completions data. + /// A mapping of tokens to maximum log probability values in this completions data. + /// The text offsets associated with tokens in this completions data. + /// A new instance for mocking. + public static CompletionsLogProbabilityModel CompletionsLogProbabilityModel(IEnumerable tokens = null, IEnumerable tokenLogProbabilities = null, IEnumerable> topLogProbabilities = null, IEnumerable textOffsets = null) + { + tokens ??= new List(); + tokenLogProbabilities ??= new List(); + topLogProbabilities ??= new List>(); + textOffsets ??= new List(); + + return new CompletionsLogProbabilityModel(tokens?.ToList(), tokenLogProbabilities?.ToList(), topLogProbabilities?.ToList(), textOffsets?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The number of tokens generated across all completions emissions. + /// The number of tokens in the provided prompts for the completions request. + /// The total number of tokens processed for the completions request and response. + /// Breakdown of tokens used in a completion. + /// A new instance for mocking. + public static CompletionsUsage CompletionsUsage(int completionTokens = default, int promptTokens = default, int totalTokens = default, CompletionsUsageCompletionTokensDetails completionTokensDetails = null) + { + return new CompletionsUsage(completionTokens, promptTokens, totalTokens, completionTokensDetails, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Tokens generated by the model for reasoning. + /// A new instance for mocking. + public static CompletionsUsageCompletionTokensDetails CompletionsUsageCompletionTokensDetails(int? reasoningTokens = null) + { + return new CompletionsUsageCompletionTokensDetails(reasoningTokens, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The contents of the system message. + /// An optional name for the participant. + /// A new instance for mocking. + public static ChatRequestSystemMessage ChatRequestSystemMessage(BinaryData content = null, string name = null) + { + return new ChatRequestSystemMessage(ChatRole.System, serializedAdditionalRawData: null, content, name); + } + + /// Initializes a new instance of . + /// The content of the message. + /// A new instance for mocking. + public static ChatMessageTextContentItem ChatMessageTextContentItem(string text = null) + { + return new ChatMessageTextContentItem("text", serializedAdditionalRawData: null, text); + } + + /// Initializes a new instance of . + /// The refusal message. + /// A new instance for mocking. + public static ChatMessageRefusalContentItem ChatMessageRefusalContentItem(string refusal = null) + { + return new ChatMessageRefusalContentItem("refusal", serializedAdditionalRawData: null, refusal); + } + + /// Initializes a new instance of . + /// An internet location, which must be accessible to the model,from which the image may be retrieved. + /// A new instance for mocking. + public static ChatMessageImageContentItem ChatMessageImageContentItem(ChatMessageImageUrl imageUrl = null) + { + return new ChatMessageImageContentItem("image_url", serializedAdditionalRawData: null, imageUrl); + } + + /// Initializes a new instance of . + /// The URL of the image. + /// + /// The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and + /// accuracy. + /// + /// A new instance for mocking. + public static ChatMessageImageUrl ChatMessageImageUrl(Uri url = null, ChatMessageImageDetailLevel? detail = null) + { + return new ChatMessageImageUrl(url, detail, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The contents of the user message, with available input types varying by selected model. + /// An optional name for the participant. + /// A new instance for mocking. + public static ChatRequestUserMessage ChatRequestUserMessage(BinaryData content = null, string name = null) + { + return new ChatRequestUserMessage(ChatRole.User, serializedAdditionalRawData: null, content, name); + } + + /// Initializes a new instance of . + /// The content of the message. + /// An optional name for the participant. + /// + /// The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// + /// The function call that must be resolved and have its output appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// + /// The refusal message by the assistant. + /// A new instance for mocking. + public static ChatRequestAssistantMessage ChatRequestAssistantMessage(BinaryData content = null, string name = null, IEnumerable toolCalls = null, FunctionCall functionCall = null, string refusal = null) + { + toolCalls ??= new List(); + + return new ChatRequestAssistantMessage( + ChatRole.Assistant, + serializedAdditionalRawData: null, + content, + name, + toolCalls?.ToList(), + functionCall, + refusal); + } + + /// Initializes a new instance of . + /// The content of the message. + /// The ID of the tool call resolved by the provided content. + /// A new instance for mocking. + public static ChatRequestToolMessage ChatRequestToolMessage(BinaryData content = null, string toolCallId = null) + { + return new ChatRequestToolMessage(ChatRole.Tool, serializedAdditionalRawData: null, content, toolCallId); + } + + /// Initializes a new instance of . + /// The name of the function that was called to produce output. + /// The output of the function as requested by the function call. + /// A new instance for mocking. + public static ChatRequestFunctionMessage ChatRequestFunctionMessage(string name = null, string content = null) + { + return new ChatRequestFunctionMessage(ChatRole.Function, serializedAdditionalRawData: null, name, content); + } + + /// Initializes a new instance of . + /// The name of the function to be called. + /// + /// A description of what the function does. The model will use this description when selecting the function and + /// interpreting its parameters. + /// + /// The parameters the function accepts, described as a JSON Schema object. + /// A new instance for mocking. + public static FunctionDefinition FunctionDefinition(string name = null, string description = null, BinaryData parameters = null) + { + return new FunctionDefinition(name, description, parameters, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The parameters to use when configuring Azure Search. + /// A new instance for mocking. + public static AzureSearchChatExtensionConfiguration AzureSearchChatExtensionConfiguration(AzureSearchChatExtensionParameters parameters = null) + { + return new AzureSearchChatExtensionConfiguration(AzureChatExtensionType.AzureSearch, serializedAdditionalRawData: null, parameters); + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The absolute endpoint path for the Azure Cognitive Search resource to use. + /// The name of the index to use as available in the referenced Azure Cognitive Search resource. + /// Customized field mapping behavior to use when interacting with the search index. + /// The query type to use with Azure Cognitive Search. + /// The additional semantic configuration for the query. + /// Search filter. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// A new instance for mocking. + public static AzureSearchChatExtensionParameters AzureSearchChatExtensionParameters(int? documentCount = null, bool? shouldRestrictResultScope = null, int? strictness = null, int? maxSearchQueries = null, bool? allowPartialResult = null, IEnumerable includeContexts = null, OnYourDataAuthenticationOptions authentication = null, Uri searchEndpoint = null, string indexName = null, AzureSearchIndexFieldMappingOptions fieldMappingOptions = null, AzureSearchQueryType? queryType = null, string semanticConfiguration = null, string filter = null, OnYourDataVectorizationSource embeddingDependency = null) + { + includeContexts ??= new List(); + + return new AzureSearchChatExtensionParameters( + documentCount, + shouldRestrictResultScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts?.ToList(), + authentication, + searchEndpoint, + indexName, + fieldMappingOptions, + queryType, + semanticConfiguration, + filter, + embeddingDependency, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The API key to use for authentication. + /// A new instance for mocking. + public static OnYourDataApiKeyAuthenticationOptions OnYourDataApiKeyAuthenticationOptions(string key = null) + { + return new OnYourDataApiKeyAuthenticationOptions(OnYourDataAuthenticationType.ApiKey, serializedAdditionalRawData: null, key); + } + + /// Initializes a new instance of . + /// The connection string to use for authentication. + /// A new instance for mocking. + public static OnYourDataConnectionStringAuthenticationOptions OnYourDataConnectionStringAuthenticationOptions(string connectionString = null) + { + return new OnYourDataConnectionStringAuthenticationOptions(OnYourDataAuthenticationType.ConnectionString, serializedAdditionalRawData: null, connectionString); + } + + /// Initializes a new instance of . + /// The key to use for authentication. + /// The key ID to use for authentication. + /// A new instance for mocking. + public static OnYourDataKeyAndKeyIdAuthenticationOptions OnYourDataKeyAndKeyIdAuthenticationOptions(string key = null, string keyId = null) + { + return new OnYourDataKeyAndKeyIdAuthenticationOptions(OnYourDataAuthenticationType.KeyAndKeyId, serializedAdditionalRawData: null, key, keyId); + } + + /// Initializes a new instance of . + /// The encoded API key to use for authentication. + /// A new instance for mocking. + public static OnYourDataEncodedApiKeyAuthenticationOptions OnYourDataEncodedApiKeyAuthenticationOptions(string encodedApiKey = null) + { + return new OnYourDataEncodedApiKeyAuthenticationOptions(OnYourDataAuthenticationType.EncodedApiKey, serializedAdditionalRawData: null, encodedApiKey); + } + + /// Initializes a new instance of . + /// The username. + /// The password. + /// A new instance for mocking. + public static OnYourDataUsernameAndPasswordAuthenticationOptions OnYourDataUsernameAndPasswordAuthenticationOptions(string username = null, string password = null) + { + return new OnYourDataUsernameAndPasswordAuthenticationOptions(OnYourDataAuthenticationType.UsernameAndPassword, serializedAdditionalRawData: null, username, password); + } + + /// Initializes a new instance of . + /// The access token to use for authentication. + /// A new instance for mocking. + public static OnYourDataAccessTokenAuthenticationOptions OnYourDataAccessTokenAuthenticationOptions(string accessToken = null) + { + return new OnYourDataAccessTokenAuthenticationOptions(OnYourDataAuthenticationType.AccessToken, serializedAdditionalRawData: null, accessToken); + } + + /// Initializes a new instance of . + /// The resource ID of the user-assigned managed identity to use for authentication. + /// A new instance for mocking. + public static OnYourDataUserAssignedManagedIdentityAuthenticationOptions OnYourDataUserAssignedManagedIdentityAuthenticationOptions(string managedIdentityResourceId = null) + { + return new OnYourDataUserAssignedManagedIdentityAuthenticationOptions(OnYourDataAuthenticationType.UserAssignedManagedIdentity, serializedAdditionalRawData: null, managedIdentityResourceId); + } + + /// Initializes a new instance of . + /// Specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. The api-version query parameter is not allowed. + /// + /// Specifies the authentication options to use when retrieving embeddings from the specified endpoint. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static OnYourDataEndpointVectorizationSource OnYourDataEndpointVectorizationSource(Uri endpoint = null, OnYourDataVectorSearchAuthenticationOptions authentication = null) + { + return new OnYourDataEndpointVectorizationSource(OnYourDataVectorizationSourceType.Endpoint, serializedAdditionalRawData: null, endpoint, authentication); + } + + /// Initializes a new instance of . + /// The API key to use for authentication. + /// A new instance for mocking. + public static OnYourDataVectorSearchApiKeyAuthenticationOptions OnYourDataVectorSearchApiKeyAuthenticationOptions(string key = null) + { + return new OnYourDataVectorSearchApiKeyAuthenticationOptions(OnYourDataVectorSearchAuthenticationType.ApiKey, serializedAdditionalRawData: null, key); + } + + /// Initializes a new instance of . + /// The access token to use for authentication. + /// A new instance for mocking. + public static OnYourDataVectorSearchAccessTokenAuthenticationOptions OnYourDataVectorSearchAccessTokenAuthenticationOptions(string accessToken = null) + { + return new OnYourDataVectorSearchAccessTokenAuthenticationOptions(OnYourDataVectorSearchAuthenticationType.AccessToken, serializedAdditionalRawData: null, accessToken); + } + + /// Initializes a new instance of . + /// The embedding model deployment name within the same Azure OpenAI resource. This enables you to use vector search without Azure OpenAI api-key and without Azure OpenAI public network access. + /// The number of dimensions the embeddings should have. Only supported in `text-embedding-3` and later models. + /// A new instance for mocking. + public static OnYourDataDeploymentNameVectorizationSource OnYourDataDeploymentNameVectorizationSource(string deploymentName = null, int? dimensions = null) + { + return new OnYourDataDeploymentNameVectorizationSource(OnYourDataVectorizationSourceType.DeploymentName, serializedAdditionalRawData: null, deploymentName, dimensions); + } + + /// Initializes a new instance of . + /// The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. + /// A new instance for mocking. + public static OnYourDataModelIdVectorizationSource OnYourDataModelIdVectorizationSource(string modelId = null) + { + return new OnYourDataModelIdVectorizationSource(OnYourDataVectorizationSourceType.ModelId, serializedAdditionalRawData: null, modelId); + } + + /// Initializes a new instance of . + /// The parameters to use when configuring Azure OpenAI CosmosDB chat extensions. + /// A new instance for mocking. + public static AzureCosmosDBChatExtensionConfiguration AzureCosmosDBChatExtensionConfiguration(AzureCosmosDBChatExtensionParameters parameters = null) + { + return new AzureCosmosDBChatExtensionConfiguration(AzureChatExtensionType.AzureCosmosDB, serializedAdditionalRawData: null, parameters); + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The MongoDB vCore database name to use with Azure Cosmos DB. + /// The name of the Azure Cosmos DB resource container. + /// The MongoDB vCore index name to use with Azure Cosmos DB. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// A new instance for mocking. + public static AzureCosmosDBChatExtensionParameters AzureCosmosDBChatExtensionParameters(int? documentCount = null, bool? shouldRestrictResultScope = null, int? strictness = null, int? maxSearchQueries = null, bool? allowPartialResult = null, IEnumerable includeContexts = null, OnYourDataAuthenticationOptions authentication = null, string databaseName = null, string containerName = null, string indexName = null, AzureCosmosDBFieldMappingOptions fieldMappingOptions = null, OnYourDataVectorizationSource embeddingDependency = null) + { + includeContexts ??= new List(); + + return new AzureCosmosDBChatExtensionParameters( + documentCount, + shouldRestrictResultScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts?.ToList(), + authentication, + databaseName, + containerName, + indexName, + fieldMappingOptions, + embeddingDependency, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The parameters to use when configuring Elasticsearch®. + /// A new instance for mocking. + public static ElasticsearchChatExtensionConfiguration ElasticsearchChatExtensionConfiguration(ElasticsearchChatExtensionParameters parameters = null) + { + return new ElasticsearchChatExtensionConfiguration(AzureChatExtensionType.Elasticsearch, serializedAdditionalRawData: null, parameters); + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The endpoint of Elasticsearch®. + /// The index name of Elasticsearch®. + /// The index field mapping options of Elasticsearch®. + /// The query type of Elasticsearch®. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// A new instance for mocking. + public static ElasticsearchChatExtensionParameters ElasticsearchChatExtensionParameters(int? documentCount = null, bool? shouldRestrictResultScope = null, int? strictness = null, int? maxSearchQueries = null, bool? allowPartialResult = null, IEnumerable includeContexts = null, OnYourDataAuthenticationOptions authentication = null, Uri endpoint = null, string indexName = null, ElasticsearchIndexFieldMappingOptions fieldMappingOptions = null, ElasticsearchQueryType? queryType = null, OnYourDataVectorizationSource embeddingDependency = null) + { + includeContexts ??= new List(); + + return new ElasticsearchChatExtensionParameters( + documentCount, + shouldRestrictResultScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts?.ToList(), + authentication, + endpoint, + indexName, + fieldMappingOptions, + queryType, + embeddingDependency, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The parameters for the MongoDB chat extension. + /// A new instance for mocking. + public static MongoDBChatExtensionConfiguration MongoDBChatExtensionConfiguration(MongoDBChatExtensionParameters parameters = null) + { + return new MongoDBChatExtensionConfiguration(AzureChatExtensionType.MongoDB, serializedAdditionalRawData: null, parameters); + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// + /// The endpoint name for MongoDB. + /// The collection name for MongoDB. + /// The database name for MongoDB. + /// The app name for MongoDB. + /// The name of the MongoDB index. + /// + /// Field mappings to apply to data used by the MongoDB data source. + /// Note that content and vector field mappings are required for MongoDB. + /// + /// The vectorization source to use with the MongoDB chat extension. + /// A new instance for mocking. + public static MongoDBChatExtensionParameters MongoDBChatExtensionParameters(int? documentCount = null, bool? shouldRestrictResultScope = null, int? strictness = null, int? maxSearchQueries = null, bool? allowPartialResult = null, IEnumerable includeContexts = null, OnYourDataUsernameAndPasswordAuthenticationOptions authentication = null, string endpoint = null, string collectionName = null, string databaseName = null, string appName = null, string indexName = null, MongoDBChatExtensionParametersFieldsMapping fieldsMapping = null, BinaryData embeddingDependency = null) + { + includeContexts ??= new List(); + + return new MongoDBChatExtensionParameters( + documentCount, + shouldRestrictResultScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts?.ToList(), + authentication, + endpoint, + collectionName, + databaseName, + appName, + indexName, + fieldsMapping, + embeddingDependency, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The parameters to use when configuring Azure OpenAI chat extensions. + /// A new instance for mocking. + public static PineconeChatExtensionConfiguration PineconeChatExtensionConfiguration(PineconeChatExtensionParameters parameters = null) + { + return new PineconeChatExtensionConfiguration(AzureChatExtensionType.Pinecone, serializedAdditionalRawData: null, parameters); + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The environment name of Pinecone. + /// The name of the Pinecone database index. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// A new instance for mocking. + public static PineconeChatExtensionParameters PineconeChatExtensionParameters(int? documentCount = null, bool? shouldRestrictResultScope = null, int? strictness = null, int? maxSearchQueries = null, bool? allowPartialResult = null, IEnumerable includeContexts = null, OnYourDataAuthenticationOptions authentication = null, string environmentName = null, string indexName = null, PineconeFieldMappingOptions fieldMappingOptions = null, OnYourDataVectorizationSource embeddingDependency = null) + { + includeContexts ??= new List(); + + return new PineconeChatExtensionParameters( + documentCount, + shouldRestrictResultScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts?.ToList(), + authentication, + environmentName, + indexName, + fieldMappingOptions, + embeddingDependency, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// A new instance for mocking. + public static ChatCompletionsJsonSchemaResponseFormat ChatCompletionsJsonSchemaResponseFormat(ChatCompletionsJsonSchemaResponseFormatJsonSchema jsonSchema = null) + { + return new ChatCompletionsJsonSchemaResponseFormat("json_schema", serializedAdditionalRawData: null, jsonSchema); + } + + /// Initializes a new instance of . + /// A description of what the response format is for, used by the model to determine how to respond in the format. + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// + /// Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + /// A new instance for mocking. + public static ChatCompletionsJsonSchemaResponseFormatJsonSchema ChatCompletionsJsonSchemaResponseFormatJsonSchema(string description = null, string name = null, BinaryData schema = null, bool? strict = null) + { + return new ChatCompletionsJsonSchemaResponseFormatJsonSchema(description, name, schema, strict, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The function definition details for the function tool. + /// A new instance for mocking. + public static ChatCompletionsFunctionToolDefinition ChatCompletionsFunctionToolDefinition(ChatCompletionsFunctionToolDefinitionFunction function = null) + { + return new ChatCompletionsFunctionToolDefinition("function", serializedAdditionalRawData: null, function); + } + + /// Initializes a new instance of . + /// A description of what the function does, used by the model to choose when and how to call the function. + /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// + /// Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling). + /// A new instance for mocking. + public static ChatCompletionsFunctionToolDefinitionFunction ChatCompletionsFunctionToolDefinitionFunction(string description = null, string name = null, BinaryData parameters = null, bool? strict = null) + { + return new ChatCompletionsFunctionToolDefinitionFunction(description, name, parameters, strict, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The function that should be called. + /// A new instance for mocking. + public static ChatCompletionsNamedFunctionToolSelection ChatCompletionsNamedFunctionToolSelection(ChatCompletionsFunctionToolSelection function = null) + { + return new ChatCompletionsNamedFunctionToolSelection("function", serializedAdditionalRawData: null, function); + } + + /// Initializes a new instance of . + /// A unique identifier associated with this chat completions response. + /// + /// The first timestamp associated with generation activity for this completions response, + /// represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. + /// + /// + /// The collection of completions choices associated with this completions response. + /// Generally, `n` choices are generated per provided prompt with a default value of 1. + /// Token limits and other settings may limit the number of choices generated. + /// + /// The model name used for this completions request. + /// + /// Content filtering results for zero or more prompts in the request. In a streaming request, + /// results for different prompts may arrive at different times or in different orders. + /// + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that + /// might impact determinism. + /// + /// Usage information for tokens processed and generated as part of this completions operation. + /// A new instance for mocking. + public static ChatCompletions ChatCompletions(string id = null, DateTimeOffset created = default, IEnumerable choices = null, string model = null, IEnumerable promptFilterResults = null, string systemFingerprint = null, CompletionsUsage usage = null) + { + choices ??= new List(); + promptFilterResults ??= new List(); + + return new ChatCompletions( + id, + created, + choices?.ToList(), + model, + promptFilterResults?.ToList(), + systemFingerprint, + usage, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The chat message for a given chat completions prompt. + /// The log probability information for this choice, as enabled via the 'logprobs' request option. + /// The ordered index associated with this chat completions choice. + /// The reason that this chat completions choice completed its generated. + /// The delta message content for a streaming response. + /// + /// Information about the content filtering category (hate, sexual, violence, self_harm), if it + /// has been detected, as well as the severity level (very_low, low, medium, high-scale that + /// determines the intensity and risk level of harmful content) and if it has been filtered or not. + /// + /// + /// Represents the output results of Azure OpenAI enhancements to chat completions, as configured via the matching input + /// provided in the request. This supplementary information is only available when using Azure OpenAI and only when the + /// request is configured to use enhancements. + /// + /// A new instance for mocking. + public static ChatChoice ChatChoice(ChatResponseMessage message = null, ChatChoiceLogProbabilityInfo logProbabilityInfo = null, int index = default, CompletionsFinishReason? finishReason = null, ChatResponseMessage internalStreamingDeltaMessage = null, ContentFilterResultsForChoice contentFilterResults = null, AzureChatEnhancements enhancements = null) + { + return new ChatChoice( + message, + logProbabilityInfo, + index, + finishReason, + internalStreamingDeltaMessage, + contentFilterResults, + enhancements, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The chat role associated with the message. + /// The refusal message generated by the model. + /// The content of the message. + /// + /// The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// + /// The function call that must be resolved and have its output appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// + /// + /// If Azure OpenAI chat extensions are configured, this array represents the incremental steps performed by those + /// extensions while processing the chat completions request. + /// + /// A new instance for mocking. + public static ChatResponseMessage ChatResponseMessage(ChatRole role = default, string refusal = null, string content = null, IEnumerable toolCalls = null, FunctionCall functionCall = null, AzureChatExtensionsMessageContext azureExtensionsContext = null) + { + toolCalls ??= new List(); + + return new ChatResponseMessage( + role, + refusal, + content, + toolCalls?.ToList(), + functionCall, + azureExtensionsContext, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The contextual information associated with the Azure chat extensions used for a chat completions request. + /// These messages describe the data source retrievals, plugin invocations, and other intermediate steps taken in the + /// course of generating a chat completions response that was augmented by capabilities from Azure OpenAI chat + /// extensions. + /// + /// The detected intent from the chat history, used to pass to the next turn to carry over the context. + /// All the retrieved documents. + /// A new instance for mocking. + public static AzureChatExtensionsMessageContext AzureChatExtensionsMessageContext(IEnumerable citations = null, string intent = null, IEnumerable allRetrievedDocuments = null) + { + citations ??= new List(); + allRetrievedDocuments ??= new List(); + + return new AzureChatExtensionsMessageContext(citations?.ToList(), intent, allRetrievedDocuments?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The content of the citation. + /// The title of the citation. + /// The URL of the citation. + /// The file path of the citation. + /// The chunk ID of the citation. + /// The rerank score of the retrieved document. + /// A new instance for mocking. + public static AzureChatExtensionDataSourceResponseCitation AzureChatExtensionDataSourceResponseCitation(string content = null, string title = null, string url = null, string filepath = null, string chunkId = null, double? rerankScore = null) + { + return new AzureChatExtensionDataSourceResponseCitation( + content, + title, + url, + filepath, + chunkId, + rerankScore, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The content of the citation. + /// The title of the citation. + /// The URL of the citation. + /// The file path of the citation. + /// The chunk ID of the citation. + /// The rerank score of the retrieved document. + /// The search queries used to retrieve the document. + /// The index of the data source. + /// The original search score of the retrieved document. + /// + /// Represents the rationale for filtering the document. If the document does not undergo filtering, + /// this field will remain unset. + /// + /// A new instance for mocking. + public static AzureChatExtensionRetrievedDocument AzureChatExtensionRetrievedDocument(string content = null, string title = null, string url = null, string filepath = null, string chunkId = null, double? rerankScore = null, IEnumerable searchQueries = null, int dataSourceIndex = default, double? originalSearchScore = null, AzureChatExtensionRetrieveDocumentFilterReason? filterReason = null) + { + searchQueries ??= new List(); + + return new AzureChatExtensionRetrievedDocument( + content, + title, + url, + filepath, + chunkId, + rerankScore, + searchQueries?.ToList(), + dataSourceIndex, + originalSearchScore, + filterReason, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. + /// The list of log probability information entries for the choice's message refusal message tokens, as requested via the 'logprobs' option. + /// A new instance for mocking. + public static ChatChoiceLogProbabilityInfo ChatChoiceLogProbabilityInfo(IEnumerable tokenLogProbabilityResults = null, IEnumerable refusal = null) + { + tokenLogProbabilityResults ??= new List(); + refusal ??= new List(); + + return new ChatChoiceLogProbabilityInfo(tokenLogProbabilityResults?.ToList(), refusal?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// The list of most likely tokens and their log probability information, as requested via 'top_logprobs'. + /// A new instance for mocking. + public static ChatTokenLogProbabilityResult ChatTokenLogProbabilityResult(string token = null, float logProbability = default, IEnumerable utf8ByteValues = null, IEnumerable topLogProbabilityEntries = null) + { + utf8ByteValues ??= new List(); + topLogProbabilityEntries ??= new List(); + + return new ChatTokenLogProbabilityResult(token, logProbability, utf8ByteValues?.ToList(), topLogProbabilityEntries?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// A new instance for mocking. + public static ChatTokenLogProbabilityInfo ChatTokenLogProbabilityInfo(string token = null, float logProbability = default, IEnumerable utf8ByteValues = null) + { + utf8ByteValues ??= new List(); + + return new ChatTokenLogProbabilityInfo(token, logProbability, utf8ByteValues?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The grounding enhancement that returns the bounding box of the objects detected in the image. + /// A new instance for mocking. + public static AzureChatEnhancements AzureChatEnhancements(AzureGroundingEnhancement grounding = null) + { + return new AzureChatEnhancements(grounding, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The lines of text detected by the grounding enhancement. + /// A new instance for mocking. + public static AzureGroundingEnhancement AzureGroundingEnhancement(IEnumerable lines = null) + { + lines ??= new List(); + + return new AzureGroundingEnhancement(lines?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The text within the line. + /// An array of spans that represent detected objects and its bounding box information. + /// A new instance for mocking. + public static AzureGroundingEnhancementLine AzureGroundingEnhancementLine(string text = null, IEnumerable spans = null) + { + spans ??= new List(); + + return new AzureGroundingEnhancementLine(text, spans?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The text content of the span that represents the detected object. + /// + /// The character offset within the text where the span begins. This offset is defined as the position of the first + /// character of the span, counting from the start of the text as Unicode codepoints. + /// + /// The length of the span in characters, measured in Unicode codepoints. + /// An array of objects representing points in the polygon that encloses the detected object. + /// A new instance for mocking. + public static AzureGroundingEnhancementLineSpan AzureGroundingEnhancementLineSpan(string text = null, int offset = default, int length = default, IEnumerable polygon = null) + { + polygon ??= new List(); + + return new AzureGroundingEnhancementLineSpan(text, offset, length, polygon?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The x-coordinate (horizontal axis) of the point. + /// The y-coordinate (vertical axis) of the point. + /// A new instance for mocking. + public static AzureGroundingEnhancementCoordinatePoint AzureGroundingEnhancementCoordinatePoint(float x = default, float y = default) + { + return new AzureGroundingEnhancementCoordinatePoint(x, y, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// A timestamp representing when this operation was started. + /// Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. + /// + /// The images generated by the operation. + /// A new instance for mocking. + public static ImageGenerations ImageGenerations(DateTimeOffset created = default, IEnumerable data = null) + { + data ??= new List(); + + return new ImageGenerations(created, data?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The URL that provides temporary access to download the generated image. + /// The complete data for an image, represented as a base64-encoded string. + /// Information about the content filtering results. + /// + /// The final prompt used by the model to generate the image. + /// Only provided with dall-3-models and only when revisions were made to the prompt. + /// + /// + /// Information about the content filtering category (hate, sexual, violence, self_harm), if + /// it has been detected, as well as the severity level (very_low, low, medium, high-scale + /// that determines the intensity and risk level of harmful content) and if it has been + /// filtered or not. Information about jailbreak content and profanity, if it has been detected, + /// and if it has been filtered or not. And information about customer block list, if it has + /// been filtered and its id. + /// + /// A new instance for mocking. + public static ImageGenerationData ImageGenerationData(Uri url = null, string base64Data = null, ImageGenerationContentFilterResults contentFilterResults = null, string revisedPrompt = null, ImageGenerationPromptFilterResults promptFilterResults = null) + { + return new ImageGenerationData( + url, + base64Data, + contentFilterResults, + revisedPrompt, + promptFilterResults, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// A new instance for mocking. + public static ImageGenerationContentFilterResults ImageGenerationContentFilterResults(ContentFilterResult sexual = null, ContentFilterResult violence = null, ContentFilterResult hate = null, ContentFilterResult selfHarm = null) + { + return new ImageGenerationContentFilterResults(sexual, violence, hate, selfHarm, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Whether a jailbreak attempt was detected in the prompt. + /// Information about customer block lists and if something was detected the associated list ID. + /// A new instance for mocking. + public static ImageGenerationPromptFilterResults ImageGenerationPromptFilterResults(ContentFilterResult sexual = null, ContentFilterResult violence = null, ContentFilterResult hate = null, ContentFilterResult selfHarm = null, ContentFilterDetectionResult profanity = null, ContentFilterDetectionResult jailbreak = null, ContentFilterDetailedResults customBlocklists = null) + { + return new ImageGenerationPromptFilterResults( + sexual, + violence, + hate, + selfHarm, + profanity, + jailbreak, + customBlocklists, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The text to generate audio for. The maximum length is 4096 characters. + /// The voice to use for text-to-speech. + /// The audio output format for the spoken text. By default, the MP3 format will be used. + /// The speed of speech for generated audio. Values are valid in the range from 0.25 to 4.0, with 1.0 the default and higher values corresponding to faster speech. + /// The model to use for this text-to-speech request. + /// A new instance for mocking. + public static SpeechGenerationOptions SpeechGenerationOptions(string input = null, SpeechVoice voice = default, SpeechGenerationResponseFormat? responseFormat = null, float? speed = null, string deploymentName = null) + { + return new SpeechGenerationOptions( + input, + voice, + responseFormat, + speed, + deploymentName, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The object type, which is always 'list'. + /// The files returned for the request. + /// A new instance for mocking. + public static FileListResponse FileListResponse(FileListResponseObject @object = default, IEnumerable data = null) + { + data ??= new List(); + + return new FileListResponse(@object, data?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The object type, which is always 'file'. + /// The identifier, which can be referenced in API endpoints. + /// The size of the file, in bytes. + /// The name of the file. + /// The Unix timestamp, in seconds, representing when this object was created. + /// The intended purpose of a file. + /// The state of the file. This field is available in Azure OpenAI only. + /// The error message with details in case processing of this file failed. This field is available in Azure OpenAI only. + /// A new instance for mocking. + public static OpenAIFile OpenAIFile(OpenAIFileObject @object = default, string id = null, int bytes = default, string filename = null, DateTimeOffset createdAt = default, FilePurpose purpose = default, FileState? status = null, string statusDetails = null) + { + return new OpenAIFile( + @object, + id, + bytes, + filename, + createdAt, + purpose, + status, + statusDetails, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// The object type, which is always 'file'. + /// A new instance for mocking. + public static FileDeletionStatus FileDeletionStatus(string id = null, bool deleted = default, FileDeletionStatusObject @object = default) + { + return new FileDeletionStatus(id, deleted, @object, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The object type, which is always list. + /// The requested list of items. + /// The first ID represented in this list. + /// The last ID represented in this list. + /// A value indicating whether there are additional values available not captured in this list. + /// A new instance for mocking. + public static OpenAIPageableListOfBatch OpenAIPageableListOfBatch(OpenAIPageableListOfBatchObject @object = default, IEnumerable data = null, string firstId = null, string lastId = null, bool? hasMore = null) + { + data ??= new List(); + + return new OpenAIPageableListOfBatch( + @object, + data?.ToList(), + firstId, + lastId, + hasMore, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The API endpoint used by the batch. + /// The ID of the input file for the batch. + /// The time frame within which the batch should be processed. + /// A set of key-value pairs that can be attached to the batch. This can be useful for storing additional information about the batch in a structured format. + /// A new instance for mocking. + public static BatchCreateRequest BatchCreateRequest(string endpoint = null, string inputFileId = null, string completionWindow = null, IDictionary metadata = null) + { + metadata ??= new Dictionary(); + + return new BatchCreateRequest(endpoint, inputFileId, completionWindow, metadata, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The Upload unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// The name of the file to be uploaded. + /// The intended number of bytes to be uploaded. + /// The intended purpose of the file. + /// The status of the Upload. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// The object type, which is always "upload". + /// The ready File object after the Upload is completed. + /// A new instance for mocking. + public static Upload Upload(string id = null, DateTimeOffset createdAt = default, string filename = null, long bytes = default, UploadPurpose purpose = default, UploadStatus status = default, DateTimeOffset expiresAt = default, UploadObject? @object = null, OpenAIFile file = null) + { + return new Upload( + id, + createdAt, + filename, + bytes, + purpose, + status, + expiresAt, + @object, + file, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The upload Part unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Part was created. + /// The ID of the Upload object that this Part was added to. + /// The object type, which is always `upload.part`. + /// Azure only field. + /// A new instance for mocking. + public static UploadPart UploadPart(string id = null, DateTimeOffset createdAt = default, string uploadId = null, UploadPartObject @object = default, string azureBlockId = null) + { + return new UploadPart( + id, + createdAt, + uploadId, + @object, + azureBlockId, + serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.Serialization.cs new file mode 100644 index 000000000000..58e0723f445a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.Serialization.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AddUploadPartRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AddUploadPartRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("data"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(Data)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(Data))) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AddUploadPartRequest 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(AddUploadPartRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAddUploadPartRequest(document.RootElement, options); + } + + internal static AddUploadPartRequest DeserializeAddUploadPartRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Stream data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("data"u8)) + { + data = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AddUploadPartRequest(data, serializedAdditionalRawData); + } + + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataRequestContent content = ToMultipartRequestContent(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() + { + MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); + content.Add(Data, "data", "data", "application/octet-stream"); + return content; + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + case "MFD": + return SerializeMultipart(options); + default: + throw new FormatException($"The model {nameof(AddUploadPartRequest)} does not support writing '{options.Format}' format."); + } + } + + AddUploadPartRequest 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 DeserializeAddUploadPartRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AddUploadPartRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AddUploadPartRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAddUploadPartRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.cs new file mode 100644 index 000000000000..9f8e672d50eb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; + +namespace Azure.AI.OpenAI +{ + /// The multipart/form-data request body of a data part addition request for an upload. + public partial class AddUploadPartRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The chunk of bytes for this Part. + /// is null. + public AddUploadPartRequest(Stream data) + { + Argument.AssertNotNull(data, nameof(data)); + + Data = data; + } + + /// Initializes a new instance of . + /// The chunk of bytes for this Part. + /// Keeps track of any properties unknown to the library. + internal AddUploadPartRequest(Stream data, IDictionary serializedAdditionalRawData) + { + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AddUploadPartRequest() + { + } + + /// The chunk of bytes for this Part. + public Stream Data { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTaskLabel.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTaskLabel.cs new file mode 100644 index 000000000000..e4669cce267d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTaskLabel.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Defines the possible descriptors for available audio operation responses. + internal readonly partial struct AudioTaskLabel : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AudioTaskLabel(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string TranscribeValue = "transcribe"; + private const string TranslateValue = "translate"; + + /// Accompanying response data resulted from an audio transcription task. + public static AudioTaskLabel Transcribe { get; } = new AudioTaskLabel(TranscribeValue); + /// Accompanying response data resulted from an audio translation task. + public static AudioTaskLabel Translate { get; } = new AudioTaskLabel(TranslateValue); + /// Determines if two values are the same. + public static bool operator ==(AudioTaskLabel left, AudioTaskLabel right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AudioTaskLabel left, AudioTaskLabel right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AudioTaskLabel(string value) => new AudioTaskLabel(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AudioTaskLabel other && Equals(other); + /// + public bool Equals(AudioTaskLabel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.Serialization.cs new file mode 100644 index 000000000000..dbc82068808b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.Serialization.cs @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranscription : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AudioTranscription)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + if (Optional.IsDefined(InternalAudioTaskLabel)) + { + writer.WritePropertyName("task"u8); + writer.WriteStringValue(InternalAudioTaskLabel.Value.ToString()); + } + if (Optional.IsDefined(Language)) + { + writer.WritePropertyName("language"u8); + writer.WriteStringValue(Language); + } + if (Optional.IsDefined(Duration)) + { + writer.WritePropertyName("duration"u8); + writer.WriteNumberValue(Convert.ToDouble(Duration.Value.ToString("s\\.FFF"))); + } + if (Optional.IsCollectionDefined(Segments)) + { + writer.WritePropertyName("segments"u8); + writer.WriteStartArray(); + foreach (var item in Segments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Words)) + { + writer.WritePropertyName("words"u8); + writer.WriteStartArray(); + foreach (var item in Words) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AudioTranscription 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(AudioTranscription)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranscription(document.RootElement, options); + } + + internal static AudioTranscription DeserializeAudioTranscription(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + AudioTaskLabel? task = default; + string language = default; + TimeSpan? duration = default; + IReadOnlyList segments = default; + IReadOnlyList words = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("task"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + task = new AudioTaskLabel(property.Value.GetString()); + continue; + } + if (property.NameEquals("language"u8)) + { + language = property.Value.GetString(); + continue; + } + if (property.NameEquals("duration"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + duration = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("segments"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AudioTranscriptionSegment.DeserializeAudioTranscriptionSegment(item, options)); + } + segments = array; + continue; + } + if (property.NameEquals("words"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AudioTranscriptionWord.DeserializeAudioTranscriptionWord(item, options)); + } + words = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranscription( + text, + task, + language, + duration, + segments ?? new ChangeTrackingList(), + words ?? new ChangeTrackingList(), + serializedAdditionalRawData); + } + + 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(AudioTranscription)} does not support writing '{options.Format}' format."); + } + } + + AudioTranscription 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 DeserializeAudioTranscription(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranscription)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranscription FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranscription(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.cs new file mode 100644 index 000000000000..af332f94ac50 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.cs @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Result information for an operation that transcribed spoken audio into written text. + public partial class AudioTranscription + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The transcribed text for the provided audio data. + /// is null. + internal AudioTranscription(string text) + { + Argument.AssertNotNull(text, nameof(text)); + + Text = text; + Segments = new ChangeTrackingList(); + Words = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The transcribed text for the provided audio data. + /// The label that describes which operation type generated the accompanying response data. + /// + /// The spoken language that was detected in the transcribed audio data. + /// This is expressed as a two-letter ISO-639-1 language code like 'en' or 'fr'. + /// + /// The total duration of the audio processed to produce accompanying transcription information. + /// A collection of information about the timing, probabilities, and other detail of each processed audio segment. + /// A collection of information about the timing of each processed word. + /// Keeps track of any properties unknown to the library. + internal AudioTranscription(string text, AudioTaskLabel? internalAudioTaskLabel, string language, TimeSpan? duration, IReadOnlyList segments, IReadOnlyList words, IDictionary serializedAdditionalRawData) + { + Text = text; + InternalAudioTaskLabel = internalAudioTaskLabel; + Language = language; + Duration = duration; + Segments = segments; + Words = words; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranscription() + { + } + + /// The transcribed text for the provided audio data. + public string Text { get; } + /// The label that describes which operation type generated the accompanying response data. + public AudioTaskLabel? InternalAudioTaskLabel { get; } + /// + /// The spoken language that was detected in the transcribed audio data. + /// This is expressed as a two-letter ISO-639-1 language code like 'en' or 'fr'. + /// + public string Language { get; } + /// The total duration of the audio processed to produce accompanying transcription information. + public TimeSpan? Duration { get; } + /// A collection of information about the timing, probabilities, and other detail of each processed audio segment. + public IReadOnlyList Segments { get; } + /// A collection of information about the timing of each processed word. + public IReadOnlyList Words { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionFormat.cs new file mode 100644 index 000000000000..fc8228609c41 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionFormat.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Defines available options for the underlying response format of output transcription information. + public readonly partial struct AudioTranscriptionFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AudioTranscriptionFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SimpleValue = "json"; + private const string VerboseValue = "verbose_json"; + private const string InternalPlainTextValue = "text"; + private const string SrtValue = "srt"; + private const string VttValue = "vtt"; + + /// Use a response body that is a JSON object containing a single 'text' field for the transcription. + public static AudioTranscriptionFormat Simple { get; } = new AudioTranscriptionFormat(SimpleValue); + /// + /// Use a response body that is a JSON object containing transcription text along with timing, segments, and other + /// metadata. + /// + public static AudioTranscriptionFormat Verbose { get; } = new AudioTranscriptionFormat(VerboseValue); + /// Use a response body that is plain text containing the raw, unannotated transcription. + public static AudioTranscriptionFormat InternalPlainText { get; } = new AudioTranscriptionFormat(InternalPlainTextValue); + /// Use a response body that is plain text in SubRip (SRT) format that also includes timing information. + public static AudioTranscriptionFormat Srt { get; } = new AudioTranscriptionFormat(SrtValue); + /// Use a response body that is plain text in Web Video Text Tracks (VTT) format that also includes timing information. + public static AudioTranscriptionFormat Vtt { get; } = new AudioTranscriptionFormat(VttValue); + /// Determines if two values are the same. + public static bool operator ==(AudioTranscriptionFormat left, AudioTranscriptionFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AudioTranscriptionFormat left, AudioTranscriptionFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AudioTranscriptionFormat(string value) => new AudioTranscriptionFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AudioTranscriptionFormat other && Equals(other); + /// + public bool Equals(AudioTranscriptionFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.Serialization.cs new file mode 100644 index 000000000000..4ccb6b9f52f3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.Serialization.cs @@ -0,0 +1,306 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranscriptionOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AudioTranscriptionOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("file"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(AudioData)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(AudioData))) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(Filename)) + { + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + } + if (Optional.IsDefined(ResponseFormat)) + { + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); + } + if (Optional.IsDefined(Language)) + { + writer.WritePropertyName("language"u8); + writer.WriteStringValue(Language); + } + if (Optional.IsDefined(Prompt)) + { + writer.WritePropertyName("prompt"u8); + writer.WriteStringValue(Prompt); + } + if (Optional.IsDefined(Temperature)) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + if (Optional.IsCollectionDefined(TimestampGranularities)) + { + writer.WritePropertyName("timestamp_granularities"u8); + writer.WriteStartArray(); + foreach (var item in TimestampGranularities) + { + writer.WriteStringValue(item.ToString()); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AudioTranscriptionOptions 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(AudioTranscriptionOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranscriptionOptions(document.RootElement, options); + } + + internal static AudioTranscriptionOptions DeserializeAudioTranscriptionOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Stream file = default; + string filename = default; + AudioTranscriptionFormat? responseFormat = default; + string language = default; + string prompt = default; + float? temperature = default; + IList timestampGranularities = default; + string model = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file"u8)) + { + file = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = new AudioTranscriptionFormat(property.Value.GetString()); + continue; + } + if (property.NameEquals("language"u8)) + { + language = property.Value.GetString(); + continue; + } + if (property.NameEquals("prompt"u8)) + { + prompt = property.Value.GetString(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("timestamp_granularities"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new AudioTranscriptionTimestampGranularity(item.GetString())); + } + timestampGranularities = array; + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranscriptionOptions( + file, + filename, + responseFormat, + language, + prompt, + temperature, + timestampGranularities ?? new ChangeTrackingList(), + model, + serializedAdditionalRawData); + } + + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataRequestContent content = ToMultipartRequestContent(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() + { + MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); + content.Add(AudioData, "file", "file", "application/octet-stream"); + if (Optional.IsDefined(Filename)) + { + content.Add(Filename, "filename"); + } + if (Optional.IsDefined(ResponseFormat)) + { + content.Add(ResponseFormat.Value.ToString(), "response_format"); + } + if (Optional.IsDefined(Language)) + { + content.Add(Language, "language"); + } + if (Optional.IsDefined(Prompt)) + { + content.Add(Prompt, "prompt"); + } + if (Optional.IsDefined(Temperature)) + { + content.Add(Temperature.Value, "temperature"); + } + if (Optional.IsCollectionDefined(TimestampGranularities)) + { + foreach (AudioTranscriptionTimestampGranularity item in TimestampGranularities) + { + content.Add(item.ToString(), "timestamp_granularities"); + } + } + if (Optional.IsDefined(DeploymentName)) + { + content.Add(DeploymentName, "model"); + } + return content; + } + + 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); + case "MFD": + return SerializeMultipart(options); + default: + throw new FormatException($"The model {nameof(AudioTranscriptionOptions)} does not support writing '{options.Format}' format."); + } + } + + AudioTranscriptionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeAudioTranscriptionOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranscriptionOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranscriptionOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranscriptionOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.cs new file mode 100644 index 000000000000..e4c0a5294401 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; + +namespace Azure.AI.OpenAI +{ + /// The configuration information for an audio transcription request. + public partial class AudioTranscriptionOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// The audio data to transcribe. This must be the binary content of a file in one of the supported media formats: + /// flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm. + /// + /// is null. + public AudioTranscriptionOptions(Stream audioData) + { + Argument.AssertNotNull(audioData, nameof(audioData)); + + AudioData = audioData; + TimestampGranularities = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// + /// The audio data to transcribe. This must be the binary content of a file in one of the supported media formats: + /// flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm. + /// + /// The optional filename or descriptive identifier to associate with with the audio data. + /// The requested format of the transcription response data, which will influence the content and detail of the result. + /// + /// The primary spoken language of the audio data to be transcribed, supplied as a two-letter ISO-639-1 language code + /// such as 'en' or 'fr'. + /// Providing this known input language is optional but may improve the accuracy and/or latency of transcription. + /// + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + /// + /// The sampling temperature, between 0 and 1. + /// Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + /// If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit. + /// + /// + /// The timestamp granularities to populate for this transcription. + /// `response_format` must be set `verbose_json` to use timestamp granularities. + /// Either or both of these options are supported: `word`, or `segment`. + /// Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. + /// + /// The model to use for this transcription request. + /// Keeps track of any properties unknown to the library. + internal AudioTranscriptionOptions(Stream audioData, string filename, AudioTranscriptionFormat? responseFormat, string language, string prompt, float? temperature, IList timestampGranularities, string deploymentName, IDictionary serializedAdditionalRawData) + { + AudioData = audioData; + Filename = filename; + ResponseFormat = responseFormat; + Language = language; + Prompt = prompt; + Temperature = temperature; + TimestampGranularities = timestampGranularities; + DeploymentName = deploymentName; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranscriptionOptions() + { + } + + /// + /// The audio data to transcribe. This must be the binary content of a file in one of the supported media formats: + /// flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm. + /// + public Stream AudioData { get; } + /// The optional filename or descriptive identifier to associate with with the audio data. + public string Filename { get; set; } + /// The requested format of the transcription response data, which will influence the content and detail of the result. + public AudioTranscriptionFormat? ResponseFormat { get; set; } + /// + /// The primary spoken language of the audio data to be transcribed, supplied as a two-letter ISO-639-1 language code + /// such as 'en' or 'fr'. + /// Providing this known input language is optional but may improve the accuracy and/or latency of transcription. + /// + public string Language { get; set; } + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + public string Prompt { get; set; } + /// + /// The sampling temperature, between 0 and 1. + /// Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + /// If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit. + /// + public float? Temperature { get; set; } + /// + /// The timestamp granularities to populate for this transcription. + /// `response_format` must be set `verbose_json` to use timestamp granularities. + /// Either or both of these options are supported: `word`, or `segment`. + /// Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. + /// + public IList TimestampGranularities { get; } + /// The model to use for this transcription request. + public string DeploymentName { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.Serialization.cs new file mode 100644 index 000000000000..a5782a864796 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.Serialization.cs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranscriptionSegment : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AudioTranscriptionSegment)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteNumberValue(Id); + writer.WritePropertyName("start"u8); + writer.WriteNumberValue(Convert.ToDouble(Start.ToString("s\\.FFF"))); + writer.WritePropertyName("end"u8); + writer.WriteNumberValue(Convert.ToDouble(End.ToString("s\\.FFF"))); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature); + writer.WritePropertyName("avg_logprob"u8); + writer.WriteNumberValue(AverageLogProbability); + writer.WritePropertyName("compression_ratio"u8); + writer.WriteNumberValue(CompressionRatio); + writer.WritePropertyName("no_speech_prob"u8); + writer.WriteNumberValue(NoSpeechProbability); + writer.WritePropertyName("tokens"u8); + writer.WriteStartArray(); + foreach (var item in Tokens) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("seek"u8); + writer.WriteNumberValue(Seek); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AudioTranscriptionSegment 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(AudioTranscriptionSegment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranscriptionSegment(document.RootElement, options); + } + + internal static AudioTranscriptionSegment DeserializeAudioTranscriptionSegment(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int id = default; + TimeSpan start = default; + TimeSpan end = default; + string text = default; + float temperature = default; + float avgLogprob = default; + float compressionRatio = default; + float noSpeechProb = default; + IReadOnlyList tokens = default; + int seek = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("start"u8)) + { + start = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("end"u8)) + { + end = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("avg_logprob"u8)) + { + avgLogprob = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("compression_ratio"u8)) + { + compressionRatio = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("no_speech_prob"u8)) + { + noSpeechProb = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("tokens"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + tokens = array; + continue; + } + if (property.NameEquals("seek"u8)) + { + seek = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranscriptionSegment( + id, + start, + end, + text, + temperature, + avgLogprob, + compressionRatio, + noSpeechProb, + tokens, + seek, + serializedAdditionalRawData); + } + + 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(AudioTranscriptionSegment)} does not support writing '{options.Format}' format."); + } + } + + AudioTranscriptionSegment 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 DeserializeAudioTranscriptionSegment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranscriptionSegment)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranscriptionSegment FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranscriptionSegment(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.cs new file mode 100644 index 000000000000..e1dd9c8fad59 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// Extended information about a single segment of transcribed audio data. + /// Segments generally represent roughly 5-10 seconds of speech. Segment boundaries typically occur between words but not + /// necessarily sentences. + /// + public partial class AudioTranscriptionSegment + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The 0-based index of this segment within a transcription. + /// The time at which this segment started relative to the beginning of the transcribed audio. + /// The time at which this segment ended relative to the beginning of the transcribed audio. + /// The transcribed text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the transcribed text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// or is null. + internal AudioTranscriptionSegment(int id, TimeSpan start, TimeSpan end, string text, float temperature, float averageLogProbability, float compressionRatio, float noSpeechProbability, IEnumerable tokens, int seek) + { + Argument.AssertNotNull(text, nameof(text)); + Argument.AssertNotNull(tokens, nameof(tokens)); + + Id = id; + Start = start; + End = end; + Text = text; + Temperature = temperature; + AverageLogProbability = averageLogProbability; + CompressionRatio = compressionRatio; + NoSpeechProbability = noSpeechProbability; + Tokens = tokens.ToList(); + Seek = seek; + } + + /// Initializes a new instance of . + /// The 0-based index of this segment within a transcription. + /// The time at which this segment started relative to the beginning of the transcribed audio. + /// The time at which this segment ended relative to the beginning of the transcribed audio. + /// The transcribed text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the transcribed text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// Keeps track of any properties unknown to the library. + internal AudioTranscriptionSegment(int id, TimeSpan start, TimeSpan end, string text, float temperature, float averageLogProbability, float compressionRatio, float noSpeechProbability, IReadOnlyList tokens, int seek, IDictionary serializedAdditionalRawData) + { + Id = id; + Start = start; + End = end; + Text = text; + Temperature = temperature; + AverageLogProbability = averageLogProbability; + CompressionRatio = compressionRatio; + NoSpeechProbability = noSpeechProbability; + Tokens = tokens; + Seek = seek; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranscriptionSegment() + { + } + + /// The 0-based index of this segment within a transcription. + public int Id { get; } + /// The time at which this segment started relative to the beginning of the transcribed audio. + public TimeSpan Start { get; } + /// The time at which this segment ended relative to the beginning of the transcribed audio. + public TimeSpan End { get; } + /// The transcribed text that was part of this audio segment. + public string Text { get; } + /// The temperature score associated with this audio segment. + public float Temperature { get; } + /// The average log probability associated with this audio segment. + public float AverageLogProbability { get; } + /// The compression ratio of this audio segment. + public float CompressionRatio { get; } + /// The probability of no speech detection within this audio segment. + public float NoSpeechProbability { get; } + /// The token IDs matching the transcribed text in this audio segment. + public IReadOnlyList Tokens { get; } + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + public int Seek { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionTimestampGranularity.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionTimestampGranularity.cs new file mode 100644 index 000000000000..b0ae51145060 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionTimestampGranularity.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Defines the timestamp granularities that can be requested on a verbose transcription response. + public readonly partial struct AudioTranscriptionTimestampGranularity : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AudioTranscriptionTimestampGranularity(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string WordValue = "word"; + private const string SegmentValue = "segment"; + + /// + /// Indicates that responses should include timing information about each transcribed word. Note that generating word + /// timestamp information will incur additional response latency. + /// + public static AudioTranscriptionTimestampGranularity Word { get; } = new AudioTranscriptionTimestampGranularity(WordValue); + /// + /// Indicates that responses should include timing and other information about each transcribed audio segment. Audio + /// segment timestamp information does not incur any additional latency. + /// + public static AudioTranscriptionTimestampGranularity Segment { get; } = new AudioTranscriptionTimestampGranularity(SegmentValue); + /// Determines if two values are the same. + public static bool operator ==(AudioTranscriptionTimestampGranularity left, AudioTranscriptionTimestampGranularity right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AudioTranscriptionTimestampGranularity left, AudioTranscriptionTimestampGranularity right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AudioTranscriptionTimestampGranularity(string value) => new AudioTranscriptionTimestampGranularity(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AudioTranscriptionTimestampGranularity other && Equals(other); + /// + public bool Equals(AudioTranscriptionTimestampGranularity other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.Serialization.cs new file mode 100644 index 000000000000..5d28770f0eed --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranscriptionWord : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AudioTranscriptionWord)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("word"u8); + writer.WriteStringValue(Word); + writer.WritePropertyName("start"u8); + writer.WriteNumberValue(Convert.ToDouble(Start.ToString("s\\.FFF"))); + writer.WritePropertyName("end"u8); + writer.WriteNumberValue(Convert.ToDouble(End.ToString("s\\.FFF"))); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AudioTranscriptionWord 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(AudioTranscriptionWord)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranscriptionWord(document.RootElement, options); + } + + internal static AudioTranscriptionWord DeserializeAudioTranscriptionWord(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string word = default; + TimeSpan start = default; + TimeSpan end = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("word"u8)) + { + word = property.Value.GetString(); + continue; + } + if (property.NameEquals("start"u8)) + { + start = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("end"u8)) + { + end = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranscriptionWord(word, start, end, serializedAdditionalRawData); + } + + 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(AudioTranscriptionWord)} does not support writing '{options.Format}' format."); + } + } + + AudioTranscriptionWord 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 DeserializeAudioTranscriptionWord(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranscriptionWord)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranscriptionWord FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranscriptionWord(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.cs new file mode 100644 index 000000000000..9fa92dfadb66 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Extended information about a single transcribed word, as provided on responses when the 'word' timestamp granularity is provided. + public partial class AudioTranscriptionWord + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The textual content of the word. + /// The start time of the word relative to the beginning of the audio, expressed in seconds. + /// The end time of the word relative to the beginning of the audio, expressed in seconds. + /// is null. + internal AudioTranscriptionWord(string word, TimeSpan start, TimeSpan end) + { + Argument.AssertNotNull(word, nameof(word)); + + Word = word; + Start = start; + End = end; + } + + /// Initializes a new instance of . + /// The textual content of the word. + /// The start time of the word relative to the beginning of the audio, expressed in seconds. + /// The end time of the word relative to the beginning of the audio, expressed in seconds. + /// Keeps track of any properties unknown to the library. + internal AudioTranscriptionWord(string word, TimeSpan start, TimeSpan end, IDictionary serializedAdditionalRawData) + { + Word = word; + Start = start; + End = end; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranscriptionWord() + { + } + + /// The textual content of the word. + public string Word { get; } + /// The start time of the word relative to the beginning of the audio, expressed in seconds. + public TimeSpan Start { get; } + /// The end time of the word relative to the beginning of the audio, expressed in seconds. + public TimeSpan End { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.Serialization.cs new file mode 100644 index 000000000000..559a1b8dbe70 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.Serialization.cs @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranslation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AudioTranslation)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + if (Optional.IsDefined(InternalAudioTaskLabel)) + { + writer.WritePropertyName("task"u8); + writer.WriteStringValue(InternalAudioTaskLabel.Value.ToString()); + } + if (Optional.IsDefined(Language)) + { + writer.WritePropertyName("language"u8); + writer.WriteStringValue(Language); + } + if (Optional.IsDefined(Duration)) + { + writer.WritePropertyName("duration"u8); + writer.WriteNumberValue(Convert.ToDouble(Duration.Value.ToString("s\\.FFF"))); + } + if (Optional.IsCollectionDefined(Segments)) + { + writer.WritePropertyName("segments"u8); + writer.WriteStartArray(); + foreach (var item in Segments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AudioTranslation 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(AudioTranslation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranslation(document.RootElement, options); + } + + internal static AudioTranslation DeserializeAudioTranslation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + AudioTaskLabel? task = default; + string language = default; + TimeSpan? duration = default; + IReadOnlyList segments = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("task"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + task = new AudioTaskLabel(property.Value.GetString()); + continue; + } + if (property.NameEquals("language"u8)) + { + language = property.Value.GetString(); + continue; + } + if (property.NameEquals("duration"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + duration = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("segments"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AudioTranslationSegment.DeserializeAudioTranslationSegment(item, options)); + } + segments = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranslation( + text, + task, + language, + duration, + segments ?? new ChangeTrackingList(), + serializedAdditionalRawData); + } + + 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(AudioTranslation)} does not support writing '{options.Format}' format."); + } + } + + AudioTranslation 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 DeserializeAudioTranslation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranslation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranslation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranslation(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.cs new file mode 100644 index 000000000000..476c481e3824 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Result information for an operation that translated spoken audio into written text. + public partial class AudioTranslation + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The translated text for the provided audio data. + /// is null. + internal AudioTranslation(string text) + { + Argument.AssertNotNull(text, nameof(text)); + + Text = text; + Segments = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The translated text for the provided audio data. + /// The label that describes which operation type generated the accompanying response data. + /// + /// The spoken language that was detected in the translated audio data. + /// This is expressed as a two-letter ISO-639-1 language code like 'en' or 'fr'. + /// + /// The total duration of the audio processed to produce accompanying translation information. + /// A collection of information about the timing, probabilities, and other detail of each processed audio segment. + /// Keeps track of any properties unknown to the library. + internal AudioTranslation(string text, AudioTaskLabel? internalAudioTaskLabel, string language, TimeSpan? duration, IReadOnlyList segments, IDictionary serializedAdditionalRawData) + { + Text = text; + InternalAudioTaskLabel = internalAudioTaskLabel; + Language = language; + Duration = duration; + Segments = segments; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranslation() + { + } + + /// The translated text for the provided audio data. + public string Text { get; } + /// The label that describes which operation type generated the accompanying response data. + public AudioTaskLabel? InternalAudioTaskLabel { get; } + /// + /// The spoken language that was detected in the translated audio data. + /// This is expressed as a two-letter ISO-639-1 language code like 'en' or 'fr'. + /// + public string Language { get; } + /// The total duration of the audio processed to produce accompanying translation information. + public TimeSpan? Duration { get; } + /// A collection of information about the timing, probabilities, and other detail of each processed audio segment. + public IReadOnlyList Segments { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationFormat.cs new file mode 100644 index 000000000000..0c8068cb6afe --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationFormat.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Defines available options for the underlying response format of output translation information. + public readonly partial struct AudioTranslationFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AudioTranslationFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SimpleValue = "json"; + private const string VerboseValue = "verbose_json"; + private const string InternalPlainTextValue = "text"; + private const string SrtValue = "srt"; + private const string VttValue = "vtt"; + + /// Use a response body that is a JSON object containing a single 'text' field for the translation. + public static AudioTranslationFormat Simple { get; } = new AudioTranslationFormat(SimpleValue); + /// + /// Use a response body that is a JSON object containing translation text along with timing, segments, and other + /// metadata. + /// + public static AudioTranslationFormat Verbose { get; } = new AudioTranslationFormat(VerboseValue); + /// Use a response body that is plain text containing the raw, unannotated translation. + public static AudioTranslationFormat InternalPlainText { get; } = new AudioTranslationFormat(InternalPlainTextValue); + /// Use a response body that is plain text in SubRip (SRT) format that also includes timing information. + public static AudioTranslationFormat Srt { get; } = new AudioTranslationFormat(SrtValue); + /// Use a response body that is plain text in Web Video Text Tracks (VTT) format that also includes timing information. + public static AudioTranslationFormat Vtt { get; } = new AudioTranslationFormat(VttValue); + /// Determines if two values are the same. + public static bool operator ==(AudioTranslationFormat left, AudioTranslationFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AudioTranslationFormat left, AudioTranslationFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AudioTranslationFormat(string value) => new AudioTranslationFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AudioTranslationFormat other && Equals(other); + /// + public bool Equals(AudioTranslationFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.Serialization.cs new file mode 100644 index 000000000000..120ed0644d67 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.Serialization.cs @@ -0,0 +1,257 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranslationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AudioTranslationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("file"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(AudioData)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(AudioData))) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(Filename)) + { + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + } + if (Optional.IsDefined(ResponseFormat)) + { + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); + } + if (Optional.IsDefined(Prompt)) + { + writer.WritePropertyName("prompt"u8); + writer.WriteStringValue(Prompt); + } + if (Optional.IsDefined(Temperature)) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AudioTranslationOptions 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(AudioTranslationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranslationOptions(document.RootElement, options); + } + + internal static AudioTranslationOptions DeserializeAudioTranslationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Stream file = default; + string filename = default; + AudioTranslationFormat? responseFormat = default; + string prompt = default; + float? temperature = default; + string model = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file"u8)) + { + file = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = new AudioTranslationFormat(property.Value.GetString()); + continue; + } + if (property.NameEquals("prompt"u8)) + { + prompt = property.Value.GetString(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranslationOptions( + file, + filename, + responseFormat, + prompt, + temperature, + model, + serializedAdditionalRawData); + } + + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataRequestContent content = ToMultipartRequestContent(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() + { + MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); + content.Add(AudioData, "file", "file", "application/octet-stream"); + if (Optional.IsDefined(Filename)) + { + content.Add(Filename, "filename"); + } + if (Optional.IsDefined(ResponseFormat)) + { + content.Add(ResponseFormat.Value.ToString(), "response_format"); + } + if (Optional.IsDefined(Prompt)) + { + content.Add(Prompt, "prompt"); + } + if (Optional.IsDefined(Temperature)) + { + content.Add(Temperature.Value, "temperature"); + } + if (Optional.IsDefined(DeploymentName)) + { + content.Add(DeploymentName, "model"); + } + return content; + } + + 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); + case "MFD": + return SerializeMultipart(options); + default: + throw new FormatException($"The model {nameof(AudioTranslationOptions)} does not support writing '{options.Format}' format."); + } + } + + AudioTranslationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data); + return DeserializeAudioTranslationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranslationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranslationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranslationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.cs new file mode 100644 index 000000000000..63936f35c61c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; + +namespace Azure.AI.OpenAI +{ + /// The configuration information for an audio translation request. + public partial class AudioTranslationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// The audio data to translate. This must be the binary content of a file in one of the supported media formats: + /// flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm. + /// + /// is null. + public AudioTranslationOptions(Stream audioData) + { + Argument.AssertNotNull(audioData, nameof(audioData)); + + AudioData = audioData; + } + + /// Initializes a new instance of . + /// + /// The audio data to translate. This must be the binary content of a file in one of the supported media formats: + /// flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm. + /// + /// The optional filename or descriptive identifier to associate with with the audio data. + /// The requested format of the translation response data, which will influence the content and detail of the result. + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + /// + /// The sampling temperature, between 0 and 1. + /// Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + /// If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit. + /// + /// The model to use for this translation request. + /// Keeps track of any properties unknown to the library. + internal AudioTranslationOptions(Stream audioData, string filename, AudioTranslationFormat? responseFormat, string prompt, float? temperature, string deploymentName, IDictionary serializedAdditionalRawData) + { + AudioData = audioData; + Filename = filename; + ResponseFormat = responseFormat; + Prompt = prompt; + Temperature = temperature; + DeploymentName = deploymentName; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranslationOptions() + { + } + + /// + /// The audio data to translate. This must be the binary content of a file in one of the supported media formats: + /// flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm. + /// + public Stream AudioData { get; } + /// The optional filename or descriptive identifier to associate with with the audio data. + public string Filename { get; set; } + /// The requested format of the translation response data, which will influence the content and detail of the result. + public AudioTranslationFormat? ResponseFormat { get; set; } + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + public string Prompt { get; set; } + /// + /// The sampling temperature, between 0 and 1. + /// Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + /// If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit. + /// + public float? Temperature { get; set; } + /// The model to use for this translation request. + public string DeploymentName { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.Serialization.cs new file mode 100644 index 000000000000..e8ec35cffb1b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.Serialization.cs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranslationSegment : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AudioTranslationSegment)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteNumberValue(Id); + writer.WritePropertyName("start"u8); + writer.WriteNumberValue(Convert.ToDouble(Start.ToString("s\\.FFF"))); + writer.WritePropertyName("end"u8); + writer.WriteNumberValue(Convert.ToDouble(End.ToString("s\\.FFF"))); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature); + writer.WritePropertyName("avg_logprob"u8); + writer.WriteNumberValue(AverageLogProbability); + writer.WritePropertyName("compression_ratio"u8); + writer.WriteNumberValue(CompressionRatio); + writer.WritePropertyName("no_speech_prob"u8); + writer.WriteNumberValue(NoSpeechProbability); + writer.WritePropertyName("tokens"u8); + writer.WriteStartArray(); + foreach (var item in Tokens) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("seek"u8); + writer.WriteNumberValue(Seek); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AudioTranslationSegment 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(AudioTranslationSegment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranslationSegment(document.RootElement, options); + } + + internal static AudioTranslationSegment DeserializeAudioTranslationSegment(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int id = default; + TimeSpan start = default; + TimeSpan end = default; + string text = default; + float temperature = default; + float avgLogprob = default; + float compressionRatio = default; + float noSpeechProb = default; + IReadOnlyList tokens = default; + int seek = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("start"u8)) + { + start = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("end"u8)) + { + end = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("avg_logprob"u8)) + { + avgLogprob = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("compression_ratio"u8)) + { + compressionRatio = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("no_speech_prob"u8)) + { + noSpeechProb = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("tokens"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + tokens = array; + continue; + } + if (property.NameEquals("seek"u8)) + { + seek = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranslationSegment( + id, + start, + end, + text, + temperature, + avgLogprob, + compressionRatio, + noSpeechProb, + tokens, + seek, + serializedAdditionalRawData); + } + + 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(AudioTranslationSegment)} does not support writing '{options.Format}' format."); + } + } + + AudioTranslationSegment 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 DeserializeAudioTranslationSegment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranslationSegment)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranslationSegment FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAudioTranslationSegment(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.cs new file mode 100644 index 000000000000..4eba8ec055ae --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// Extended information about a single segment of translated audio data. + /// Segments generally represent roughly 5-10 seconds of speech. Segment boundaries typically occur between words but not + /// necessarily sentences. + /// + public partial class AudioTranslationSegment + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The 0-based index of this segment within a translation. + /// The time at which this segment started relative to the beginning of the translated audio. + /// The time at which this segment ended relative to the beginning of the translated audio. + /// The translated text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the translated text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// or is null. + internal AudioTranslationSegment(int id, TimeSpan start, TimeSpan end, string text, float temperature, float averageLogProbability, float compressionRatio, float noSpeechProbability, IEnumerable tokens, int seek) + { + Argument.AssertNotNull(text, nameof(text)); + Argument.AssertNotNull(tokens, nameof(tokens)); + + Id = id; + Start = start; + End = end; + Text = text; + Temperature = temperature; + AverageLogProbability = averageLogProbability; + CompressionRatio = compressionRatio; + NoSpeechProbability = noSpeechProbability; + Tokens = tokens.ToList(); + Seek = seek; + } + + /// Initializes a new instance of . + /// The 0-based index of this segment within a translation. + /// The time at which this segment started relative to the beginning of the translated audio. + /// The time at which this segment ended relative to the beginning of the translated audio. + /// The translated text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the translated text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// Keeps track of any properties unknown to the library. + internal AudioTranslationSegment(int id, TimeSpan start, TimeSpan end, string text, float temperature, float averageLogProbability, float compressionRatio, float noSpeechProbability, IReadOnlyList tokens, int seek, IDictionary serializedAdditionalRawData) + { + Id = id; + Start = start; + End = end; + Text = text; + Temperature = temperature; + AverageLogProbability = averageLogProbability; + CompressionRatio = compressionRatio; + NoSpeechProbability = noSpeechProbability; + Tokens = tokens; + Seek = seek; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranslationSegment() + { + } + + /// The 0-based index of this segment within a translation. + public int Id { get; } + /// The time at which this segment started relative to the beginning of the translated audio. + public TimeSpan Start { get; } + /// The time at which this segment ended relative to the beginning of the translated audio. + public TimeSpan End { get; } + /// The translated text that was part of this audio segment. + public string Text { get; } + /// The temperature score associated with this audio segment. + public float Temperature { get; } + /// The average log probability associated with this audio segment. + public float AverageLogProbability { get; } + /// The compression ratio of this audio segment. + public float CompressionRatio { get; } + /// The probability of no speech detection within this audio segment. + public float NoSpeechProbability { get; } + /// The token IDs matching the translated text in this audio segment. + public IReadOnlyList Tokens { get; } + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + public int Seek { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.Serialization.cs new file mode 100644 index 000000000000..1a12e637d389 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.Serialization.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatEnhancementConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureChatEnhancementConfiguration)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Grounding)) + { + writer.WritePropertyName("grounding"u8); + writer.WriteObjectValue(Grounding, options); + } + if (Optional.IsDefined(Ocr)) + { + writer.WritePropertyName("ocr"u8); + writer.WriteObjectValue(Ocr, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureChatEnhancementConfiguration 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(AzureChatEnhancementConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatEnhancementConfiguration(document.RootElement, options); + } + + internal static AzureChatEnhancementConfiguration DeserializeAzureChatEnhancementConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureChatGroundingEnhancementConfiguration grounding = default; + AzureChatOCREnhancementConfiguration ocr = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("grounding"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + grounding = AzureChatGroundingEnhancementConfiguration.DeserializeAzureChatGroundingEnhancementConfiguration(property.Value, options); + continue; + } + if (property.NameEquals("ocr"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + ocr = AzureChatOCREnhancementConfiguration.DeserializeAzureChatOCREnhancementConfiguration(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatEnhancementConfiguration(grounding, ocr, serializedAdditionalRawData); + } + + 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(AzureChatEnhancementConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureChatEnhancementConfiguration 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 DeserializeAzureChatEnhancementConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatEnhancementConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatEnhancementConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureChatEnhancementConfiguration(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.cs new file mode 100644 index 000000000000..9abaf36c33a7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of the available Azure OpenAI enhancement configurations. + public partial class AzureChatEnhancementConfiguration + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public AzureChatEnhancementConfiguration() + { + } + + /// Initializes a new instance of . + /// A representation of the available options for the Azure OpenAI grounding enhancement. + /// A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. + /// Keeps track of any properties unknown to the library. + internal AzureChatEnhancementConfiguration(AzureChatGroundingEnhancementConfiguration grounding, AzureChatOCREnhancementConfiguration ocr, IDictionary serializedAdditionalRawData) + { + Grounding = grounding; + Ocr = ocr; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A representation of the available options for the Azure OpenAI grounding enhancement. + public AzureChatGroundingEnhancementConfiguration Grounding { get; set; } + /// A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. + public AzureChatOCREnhancementConfiguration Ocr { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.Serialization.cs new file mode 100644 index 000000000000..8d4215b9c075 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatEnhancements : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureChatEnhancements)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Grounding)) + { + writer.WritePropertyName("grounding"u8); + writer.WriteObjectValue(Grounding, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureChatEnhancements 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(AzureChatEnhancements)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatEnhancements(document.RootElement, options); + } + + internal static AzureChatEnhancements DeserializeAzureChatEnhancements(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureGroundingEnhancement grounding = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("grounding"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + grounding = AzureGroundingEnhancement.DeserializeAzureGroundingEnhancement(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatEnhancements(grounding, serializedAdditionalRawData); + } + + 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(AzureChatEnhancements)} does not support writing '{options.Format}' format."); + } + } + + AzureChatEnhancements 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 DeserializeAzureChatEnhancements(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatEnhancements)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatEnhancements FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureChatEnhancements(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleErrorResponse.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.cs similarity index 61% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleErrorResponse.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.cs index 6aafb0c3d308..113d9a88ea0a 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleErrorResponse.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -7,8 +10,11 @@ namespace Azure.AI.OpenAI { - /// A structured representation of an error an Azure OpenAI request. - internal partial class AzureOpenAIDalleErrorResponse + /// + /// Represents the output results of Azure enhancements to chat completions, as configured via the matching input provided + /// in the request. + /// + public partial class AzureChatEnhancements { /// /// Keeps track of any properties unknown to the library. @@ -40,22 +46,23 @@ internal partial class AzureOpenAIDalleErrorResponse /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal AzureOpenAIDalleErrorResponse() + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal AzureChatEnhancements() { } - /// Initializes a new instance of . - /// + /// Initializes a new instance of . + /// The grounding enhancement that returns the bounding box of the objects detected in the image. /// Keeps track of any properties unknown to the library. - internal AzureOpenAIDalleErrorResponse(AzureOpenAIDalleError error, IDictionary serializedAdditionalRawData) + internal AzureChatEnhancements(AzureGroundingEnhancement grounding, IDictionary serializedAdditionalRawData) { - Error = error; - SerializedAdditionalRawData = serializedAdditionalRawData; + Grounding = grounding; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Gets the error. - public AzureOpenAIDalleError Error { get; } + /// The grounding enhancement that returns the bounding box of the objects detected in the image. + public AzureGroundingEnhancement Grounding { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..58d4f9d5a503 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownAzureChatExtensionConfiguration))] + public partial class AzureChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureChatExtensionConfiguration 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(AzureChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatExtensionConfiguration(document.RootElement, options); + } + + internal static AzureChatExtensionConfiguration DeserializeAzureChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "azure_cosmos_db": return AzureCosmosDBChatExtensionConfiguration.DeserializeAzureCosmosDBChatExtensionConfiguration(element, options); + case "azure_search": return AzureSearchChatExtensionConfiguration.DeserializeAzureSearchChatExtensionConfiguration(element, options); + case "elasticsearch": return ElasticsearchChatExtensionConfiguration.DeserializeElasticsearchChatExtensionConfiguration(element, options); + case "mongo_db": return MongoDBChatExtensionConfiguration.DeserializeMongoDBChatExtensionConfiguration(element, options); + case "pinecone": return PineconeChatExtensionConfiguration.DeserializePineconeChatExtensionConfiguration(element, options); + } + } + return UnknownAzureChatExtensionConfiguration.DeserializeUnknownAzureChatExtensionConfiguration(element, 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(AzureChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureChatExtensionConfiguration 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 DeserializeAzureChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.cs new file mode 100644 index 000000000000..689f1809d2b8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat + /// completions request that should use Azure OpenAI chat extensions to augment the response behavior. + /// The use of this configuration is compatible only with Azure OpenAI. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + public abstract partial class AzureChatExtensionConfiguration + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected AzureChatExtensionConfiguration() + { + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + internal AzureChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + internal AzureChatExtensionType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCitation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.Serialization.cs similarity index 56% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCitation.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.Serialization.cs index d361f85eecfd..792a06a92a2e 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCitation.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.Serialization.cs @@ -1,64 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - public partial class ChatCitation : IJsonModel + public partial class AzureChatExtensionDataSourceResponseCitation : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCitation)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(AzureChatExtensionDataSourceResponseCitation)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("content") != true) - { - writer.WritePropertyName("content"u8); - writer.WriteStringValue(Content); - } - if (SerializedAdditionalRawData?.ContainsKey("title") != true && Optional.IsDefined(Title)) + writer.WritePropertyName("content"u8); + writer.WriteStringValue(Content); + if (Optional.IsDefined(Title)) { writer.WritePropertyName("title"u8); writer.WriteStringValue(Title); } - if (SerializedAdditionalRawData?.ContainsKey("url") != true && Optional.IsDefined(Uri)) + if (Optional.IsDefined(Url)) { writer.WritePropertyName("url"u8); - writer.WriteStringValue(Uri.AbsoluteUri); + writer.WriteStringValue(Url); } - if (SerializedAdditionalRawData?.ContainsKey("filepath") != true && Optional.IsDefined(FilePath)) + if (Optional.IsDefined(Filepath)) { writer.WritePropertyName("filepath"u8); - writer.WriteStringValue(FilePath); + writer.WriteStringValue(Filepath); } - if (SerializedAdditionalRawData?.ContainsKey("chunk_id") != true && Optional.IsDefined(ChunkId)) + if (Optional.IsDefined(ChunkId)) { writer.WritePropertyName("chunk_id"u8); writer.WriteStringValue(ChunkId); } - if (SerializedAdditionalRawData?.ContainsKey("rerank_score") != true && Optional.IsDefined(RerankScore)) + if (Optional.IsDefined(RerankScore)) { writer.WritePropertyName("rerank_score"u8); writer.WriteNumberValue(RerankScore.Value); } - if (SerializedAdditionalRawData != null) + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -73,19 +71,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpti writer.WriteEndObject(); } - ChatCitation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AzureChatExtensionDataSourceResponseCitation 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(ChatCitation)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(AzureChatExtensionDataSourceResponseCitation)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatCitation(document.RootElement, options); + return DeserializeAzureChatExtensionDataSourceResponseCitation(document.RootElement, options); } - internal static ChatCitation DeserializeChatCitation(JsonElement element, ModelReaderWriterOptions options = null) + internal static AzureChatExtensionDataSourceResponseCitation DeserializeAzureChatExtensionDataSourceResponseCitation(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -95,7 +93,7 @@ internal static ChatCitation DeserializeChatCitation(JsonElement element, ModelR } string content = default; string title = default; - Uri url = default; + string url = default; string filepath = default; string chunkId = default; double? rerankScore = default; @@ -115,11 +113,7 @@ internal static ChatCitation DeserializeChatCitation(JsonElement element, ModelR } if (property.NameEquals("url"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - url = new Uri(property.Value.GetString()); + url = property.Value.GetString(); continue; } if (property.NameEquals("filepath"u8)) @@ -143,12 +137,11 @@ internal static ChatCitation DeserializeChatCitation(JsonElement element, ModelR } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new ChatCitation( + return new AzureChatExtensionDataSourceResponseCitation( content, title, url, @@ -158,49 +151,51 @@ internal static ChatCitation DeserializeChatCitation(JsonElement element, ModelR 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(ChatCitation)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(AzureChatExtensionDataSourceResponseCitation)} does not support writing '{options.Format}' format."); } } - ChatCitation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + AzureChatExtensionDataSourceResponseCitation 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 DeserializeChatCitation(document.RootElement, options); + return DeserializeAzureChatExtensionDataSourceResponseCitation(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ChatCitation)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(AzureChatExtensionDataSourceResponseCitation)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ChatCitation FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static AzureChatExtensionDataSourceResponseCitation FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeChatCitation(document.RootElement); + return DeserializeAzureChatExtensionDataSourceResponseCitation(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCitation.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.cs similarity index 50% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCitation.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.cs index 6d49dbb6950e..b07ff2f62a95 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCitation.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -5,10 +8,14 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - /// The AzureChatMessageContextCitation. - public partial class ChatCitation + /// + /// A single instance of additional context information available when Azure OpenAI chat extensions are involved + /// in the generation of a corresponding chat completions response. This context information is only populated when + /// using an Azure OpenAI request configured to use a matching extension. + /// + public partial class AzureChatExtensionDataSourceResponseCitation { /// /// Keeps track of any properties unknown to the library. @@ -40,48 +47,53 @@ public partial class ChatCitation /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . /// The content of the citation. /// is null. - internal ChatCitation(string content) + internal AzureChatExtensionDataSourceResponseCitation(string content) { Argument.AssertNotNull(content, nameof(content)); Content = content; } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The content of the citation. - /// The title for the citation. - /// The URL of the citation. - /// The file path for the citation. - /// The chunk ID for the citation. - /// The rerank score for the retrieval. + /// The title of the citation. + /// The URL of the citation. + /// The file path of the citation. + /// The chunk ID of the citation. + /// The rerank score of the retrieved document. /// Keeps track of any properties unknown to the library. - internal ChatCitation(string content, string title, Uri uri, string filePath, string chunkId, double? rerankScore, IDictionary serializedAdditionalRawData) + internal AzureChatExtensionDataSourceResponseCitation(string content, string title, string url, string filepath, string chunkId, double? rerankScore, IDictionary serializedAdditionalRawData) { Content = content; Title = title; - Uri = uri; - FilePath = filePath; + Url = url; + Filepath = filepath; ChunkId = chunkId; RerankScore = rerankScore; - SerializedAdditionalRawData = serializedAdditionalRawData; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal ChatCitation() + /// Initializes a new instance of for deserialization. + internal AzureChatExtensionDataSourceResponseCitation() { } /// The content of the citation. public string Content { get; } - /// The title for the citation. + /// The title of the citation. public string Title { get; } - /// The chunk ID for the citation. + /// The URL of the citation. + public string Url { get; } + /// The file path of the citation. + public string Filepath { get; } + /// The chunk ID of the citation. public string ChunkId { get; } - /// The rerank score for the retrieval. + /// The rerank score of the retrieved document. public double? RerankScore { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.Serialization.cs new file mode 100644 index 000000000000..97679b72fb36 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.Serialization.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.AI.OpenAI +{ + internal static partial class AzureChatExtensionRetrieveDocumentFilterReasonExtensions + { + public static string ToSerialString(this AzureChatExtensionRetrieveDocumentFilterReason value) => value switch + { + AzureChatExtensionRetrieveDocumentFilterReason.Score => "score", + AzureChatExtensionRetrieveDocumentFilterReason.Rerank => "rerank", + _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown AzureChatExtensionRetrieveDocumentFilterReason value.") + }; + + public static AzureChatExtensionRetrieveDocumentFilterReason ToAzureChatExtensionRetrieveDocumentFilterReason(this string value) + { + if (StringComparer.OrdinalIgnoreCase.Equals(value, "score")) return AzureChatExtensionRetrieveDocumentFilterReason.Score; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "rerank")) return AzureChatExtensionRetrieveDocumentFilterReason.Rerank; + throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown AzureChatExtensionRetrieveDocumentFilterReason value."); + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.cs new file mode 100644 index 000000000000..a0ff002c2627 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.AI.OpenAI +{ + /// The reason for filtering the retrieved document. + public enum AzureChatExtensionRetrieveDocumentFilterReason + { + /// The document is filtered by original search score threshold defined by `strictness` configure. + Score, + /// The document is not filtered by original search score threshold, but is filtered by rerank score and `top_n_documents` configure. + Rerank + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRetrievedDocument.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.Serialization.cs similarity index 57% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRetrievedDocument.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.Serialization.cs index 2ab576c95b61..109482b70d3d 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRetrievedDocument.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.Serialization.cs @@ -1,89 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - public partial class ChatRetrievedDocument : IJsonModel + public partial class AzureChatExtensionRetrievedDocument : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatRetrievedDocument)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(AzureChatExtensionRetrievedDocument)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("content") != true) - { - writer.WritePropertyName("content"u8); - writer.WriteStringValue(Content); - } - if (SerializedAdditionalRawData?.ContainsKey("title") != true && Optional.IsDefined(Title)) + writer.WritePropertyName("content"u8); + writer.WriteStringValue(Content); + if (Optional.IsDefined(Title)) { writer.WritePropertyName("title"u8); writer.WriteStringValue(Title); } - if (SerializedAdditionalRawData?.ContainsKey("url") != true && Optional.IsDefined(Uri)) + if (Optional.IsDefined(Url)) { writer.WritePropertyName("url"u8); - writer.WriteStringValue(Uri.AbsoluteUri); + writer.WriteStringValue(Url); } - if (SerializedAdditionalRawData?.ContainsKey("filepath") != true && Optional.IsDefined(FilePath)) + if (Optional.IsDefined(Filepath)) { writer.WritePropertyName("filepath"u8); - writer.WriteStringValue(FilePath); + writer.WriteStringValue(Filepath); } - if (SerializedAdditionalRawData?.ContainsKey("chunk_id") != true && Optional.IsDefined(ChunkId)) + if (Optional.IsDefined(ChunkId)) { writer.WritePropertyName("chunk_id"u8); writer.WriteStringValue(ChunkId); } - if (SerializedAdditionalRawData?.ContainsKey("rerank_score") != true && Optional.IsDefined(RerankScore)) + if (Optional.IsDefined(RerankScore)) { writer.WritePropertyName("rerank_score"u8); writer.WriteNumberValue(RerankScore.Value); } - if (SerializedAdditionalRawData?.ContainsKey("search_queries") != true) - { - writer.WritePropertyName("search_queries"u8); - writer.WriteStartArray(); - foreach (var item in SearchQueries) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData?.ContainsKey("data_source_index") != true) + writer.WritePropertyName("search_queries"u8); + writer.WriteStartArray(); + foreach (var item in SearchQueries) { - writer.WritePropertyName("data_source_index"u8); - writer.WriteNumberValue(DataSourceIndex); + writer.WriteStringValue(item); } - if (SerializedAdditionalRawData?.ContainsKey("original_search_score") != true && Optional.IsDefined(OriginalSearchScore)) + writer.WriteEndArray(); + writer.WritePropertyName("data_source_index"u8); + writer.WriteNumberValue(DataSourceIndex); + if (Optional.IsDefined(OriginalSearchScore)) { writer.WritePropertyName("original_search_score"u8); writer.WriteNumberValue(OriginalSearchScore.Value); } - if (SerializedAdditionalRawData?.ContainsKey("filter_reason") != true && Optional.IsDefined(FilterReason)) + if (Optional.IsDefined(FilterReason)) { writer.WritePropertyName("filter_reason"u8); - writer.WriteStringValue(FilterReason.Value.ToString()); + writer.WriteStringValue(FilterReason.Value.ToSerialString()); } - if (SerializedAdditionalRawData != null) + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -98,19 +90,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW writer.WriteEndObject(); } - ChatRetrievedDocument IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AzureChatExtensionRetrievedDocument 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(ChatRetrievedDocument)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(AzureChatExtensionRetrievedDocument)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatRetrievedDocument(document.RootElement, options); + return DeserializeAzureChatExtensionRetrievedDocument(document.RootElement, options); } - internal static ChatRetrievedDocument DeserializeChatRetrievedDocument(JsonElement element, ModelReaderWriterOptions options = null) + internal static AzureChatExtensionRetrievedDocument DeserializeAzureChatExtensionRetrievedDocument(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -120,14 +112,14 @@ internal static ChatRetrievedDocument DeserializeChatRetrievedDocument(JsonEleme } string content = default; string title = default; - Uri url = default; + string url = default; string filepath = default; string chunkId = default; double? rerankScore = default; IReadOnlyList searchQueries = default; int dataSourceIndex = default; double? originalSearchScore = default; - ChatDocumentFilterReason? filterReason = default; + AzureChatExtensionRetrieveDocumentFilterReason? filterReason = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -144,11 +136,7 @@ internal static ChatRetrievedDocument DeserializeChatRetrievedDocument(JsonEleme } if (property.NameEquals("url"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - url = new Uri(property.Value.GetString()); + url = property.Value.GetString(); continue; } if (property.NameEquals("filepath"u8)) @@ -200,17 +188,16 @@ internal static ChatRetrievedDocument DeserializeChatRetrievedDocument(JsonEleme { continue; } - filterReason = new ChatDocumentFilterReason(property.Value.GetString()); + filterReason = property.Value.GetString().ToAzureChatExtensionRetrieveDocumentFilterReason(); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new ChatRetrievedDocument( + return new AzureChatExtensionRetrievedDocument( content, title, url, @@ -224,49 +211,51 @@ internal static ChatRetrievedDocument DeserializeChatRetrievedDocument(JsonEleme 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(ChatRetrievedDocument)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(AzureChatExtensionRetrievedDocument)} does not support writing '{options.Format}' format."); } } - ChatRetrievedDocument IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + AzureChatExtensionRetrievedDocument 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 DeserializeChatRetrievedDocument(document.RootElement, options); + return DeserializeAzureChatExtensionRetrievedDocument(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ChatRetrievedDocument)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(AzureChatExtensionRetrievedDocument)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ChatRetrievedDocument FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static AzureChatExtensionRetrievedDocument FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeChatRetrievedDocument(document.RootElement); + return DeserializeAzureChatExtensionRetrievedDocument(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.cs new file mode 100644 index 000000000000..8ee20083b474 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The retrieved document. + public partial class AzureChatExtensionRetrievedDocument + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The content of the citation. + /// The search queries used to retrieve the document. + /// The index of the data source. + /// or is null. + internal AzureChatExtensionRetrievedDocument(string content, IEnumerable searchQueries, int dataSourceIndex) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNull(searchQueries, nameof(searchQueries)); + + Content = content; + SearchQueries = searchQueries.ToList(); + DataSourceIndex = dataSourceIndex; + } + + /// Initializes a new instance of . + /// The content of the citation. + /// The title of the citation. + /// The URL of the citation. + /// The file path of the citation. + /// The chunk ID of the citation. + /// The rerank score of the retrieved document. + /// The search queries used to retrieve the document. + /// The index of the data source. + /// The original search score of the retrieved document. + /// + /// Represents the rationale for filtering the document. If the document does not undergo filtering, + /// this field will remain unset. + /// + /// Keeps track of any properties unknown to the library. + internal AzureChatExtensionRetrievedDocument(string content, string title, string url, string filepath, string chunkId, double? rerankScore, IReadOnlyList searchQueries, int dataSourceIndex, double? originalSearchScore, AzureChatExtensionRetrieveDocumentFilterReason? filterReason, IDictionary serializedAdditionalRawData) + { + Content = content; + Title = title; + Url = url; + Filepath = filepath; + ChunkId = chunkId; + RerankScore = rerankScore; + SearchQueries = searchQueries; + DataSourceIndex = dataSourceIndex; + OriginalSearchScore = originalSearchScore; + FilterReason = filterReason; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureChatExtensionRetrievedDocument() + { + } + + /// The content of the citation. + public string Content { get; } + /// The title of the citation. + public string Title { get; } + /// The URL of the citation. + public string Url { get; } + /// The file path of the citation. + public string Filepath { get; } + /// The chunk ID of the citation. + public string ChunkId { get; } + /// The rerank score of the retrieved document. + public double? RerankScore { get; } + /// The search queries used to retrieve the document. + public IReadOnlyList SearchQueries { get; } + /// The index of the data source. + public int DataSourceIndex { get; } + /// The original search score of the retrieved document. + public double? OriginalSearchScore { get; } + /// + /// Represents the rationale for filtering the document. If the document does not undergo filtering, + /// this field will remain unset. + /// + public AzureChatExtensionRetrieveDocumentFilterReason? FilterReason { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionType.cs new file mode 100644 index 000000000000..43ed79a551d4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionType.cs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// + /// A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat + /// completions request that should use Azure OpenAI chat extensions to augment the response behavior. + /// The use of this configuration is compatible only with Azure OpenAI. + /// + internal readonly partial struct AzureChatExtensionType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AzureChatExtensionType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AzureSearchValue = "azure_search"; + private const string AzureCosmosDBValue = "azure_cosmos_db"; + private const string ElasticsearchValue = "elasticsearch"; + private const string PineconeValue = "pinecone"; + private const string MongoDBValue = "mongo_db"; + + /// Represents the use of Azure AI Search as an Azure OpenAI chat extension. + public static AzureChatExtensionType AzureSearch { get; } = new AzureChatExtensionType(AzureSearchValue); + /// Represents the use of Azure Cosmos DB as an Azure OpenAI chat extension. + public static AzureChatExtensionType AzureCosmosDB { get; } = new AzureChatExtensionType(AzureCosmosDBValue); + /// Represents the use of Elasticsearch® index as an Azure OpenAI chat extension. + public static AzureChatExtensionType Elasticsearch { get; } = new AzureChatExtensionType(ElasticsearchValue); + /// Represents the use of Pinecone index as an Azure OpenAI chat extension. + public static AzureChatExtensionType Pinecone { get; } = new AzureChatExtensionType(PineconeValue); + /// Represents the use of a MongoDB chat extension. + public static AzureChatExtensionType MongoDB { get; } = new AzureChatExtensionType(MongoDBValue); + /// Determines if two values are the same. + public static bool operator ==(AzureChatExtensionType left, AzureChatExtensionType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AzureChatExtensionType left, AzureChatExtensionType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AzureChatExtensionType(string value) => new AzureChatExtensionType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AzureChatExtensionType other && Equals(other); + /// + public bool Equals(AzureChatExtensionType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.Serialization.cs new file mode 100644 index 000000000000..5a1352cfa877 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.Serialization.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatExtensionsMessageContext : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureChatExtensionsMessageContext)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsCollectionDefined(Citations)) + { + writer.WritePropertyName("citations"u8); + writer.WriteStartArray(); + foreach (var item in Citations) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Intent)) + { + writer.WritePropertyName("intent"u8); + writer.WriteStringValue(Intent); + } + if (Optional.IsCollectionDefined(AllRetrievedDocuments)) + { + writer.WritePropertyName("all_retrieved_documents"u8); + writer.WriteStartArray(); + foreach (var item in AllRetrievedDocuments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureChatExtensionsMessageContext 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(AzureChatExtensionsMessageContext)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatExtensionsMessageContext(document.RootElement, options); + } + + internal static AzureChatExtensionsMessageContext DeserializeAzureChatExtensionsMessageContext(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList citations = default; + string intent = default; + IReadOnlyList allRetrievedDocuments = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("citations"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureChatExtensionDataSourceResponseCitation.DeserializeAzureChatExtensionDataSourceResponseCitation(item, options)); + } + citations = array; + continue; + } + if (property.NameEquals("intent"u8)) + { + intent = property.Value.GetString(); + continue; + } + if (property.NameEquals("all_retrieved_documents"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureChatExtensionRetrievedDocument.DeserializeAzureChatExtensionRetrievedDocument(item, options)); + } + allRetrievedDocuments = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatExtensionsMessageContext(citations ?? new ChangeTrackingList(), intent, allRetrievedDocuments ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + 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(AzureChatExtensionsMessageContext)} does not support writing '{options.Format}' format."); + } + } + + AzureChatExtensionsMessageContext 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 DeserializeAzureChatExtensionsMessageContext(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatExtensionsMessageContext)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatExtensionsMessageContext FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureChatExtensionsMessageContext(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.cs new file mode 100644 index 000000000000..0591400215bc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A representation of the additional context information available when Azure OpenAI chat extensions are involved + /// in the generation of a corresponding chat completions response. This context information is only populated when + /// using an Azure OpenAI request configured to use a matching extension. + /// + public partial class AzureChatExtensionsMessageContext + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal AzureChatExtensionsMessageContext() + { + Citations = new ChangeTrackingList(); + AllRetrievedDocuments = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// + /// The contextual information associated with the Azure chat extensions used for a chat completions request. + /// These messages describe the data source retrievals, plugin invocations, and other intermediate steps taken in the + /// course of generating a chat completions response that was augmented by capabilities from Azure OpenAI chat + /// extensions. + /// + /// The detected intent from the chat history, used to pass to the next turn to carry over the context. + /// All the retrieved documents. + /// Keeps track of any properties unknown to the library. + internal AzureChatExtensionsMessageContext(IReadOnlyList citations, string intent, IReadOnlyList allRetrievedDocuments, IDictionary serializedAdditionalRawData) + { + Citations = citations; + Intent = intent; + AllRetrievedDocuments = allRetrievedDocuments; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The contextual information associated with the Azure chat extensions used for a chat completions request. + /// These messages describe the data source retrievals, plugin invocations, and other intermediate steps taken in the + /// course of generating a chat completions response that was augmented by capabilities from Azure OpenAI chat + /// extensions. + /// + public IReadOnlyList Citations { get; } + /// The detected intent from the chat history, used to pass to the next turn to carry over the context. + public string Intent { get; } + /// All the retrieved documents. + public IReadOnlyList AllRetrievedDocuments { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.Serialization.cs new file mode 100644 index 000000000000..9f1f19aa97af --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatGroundingEnhancementConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureChatGroundingEnhancementConfiguration)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureChatGroundingEnhancementConfiguration 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(AzureChatGroundingEnhancementConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatGroundingEnhancementConfiguration(document.RootElement, options); + } + + internal static AzureChatGroundingEnhancementConfiguration DeserializeAzureChatGroundingEnhancementConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool enabled = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatGroundingEnhancementConfiguration(enabled, serializedAdditionalRawData); + } + + 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(AzureChatGroundingEnhancementConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureChatGroundingEnhancementConfiguration 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 DeserializeAzureChatGroundingEnhancementConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatGroundingEnhancementConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatGroundingEnhancementConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureChatGroundingEnhancementConfiguration(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.cs new file mode 100644 index 000000000000..8e14c4e438d2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of the available options for the Azure OpenAI grounding enhancement. + public partial class AzureChatGroundingEnhancementConfiguration + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Specifies whether the enhancement is enabled. + public AzureChatGroundingEnhancementConfiguration(bool enabled) + { + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Specifies whether the enhancement is enabled. + /// Keeps track of any properties unknown to the library. + internal AzureChatGroundingEnhancementConfiguration(bool enabled, IDictionary serializedAdditionalRawData) + { + Enabled = enabled; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureChatGroundingEnhancementConfiguration() + { + } + + /// Specifies whether the enhancement is enabled. + public bool Enabled { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.Serialization.cs new file mode 100644 index 000000000000..058d5d43c564 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatOCREnhancementConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureChatOCREnhancementConfiguration)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureChatOCREnhancementConfiguration 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(AzureChatOCREnhancementConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatOCREnhancementConfiguration(document.RootElement, options); + } + + internal static AzureChatOCREnhancementConfiguration DeserializeAzureChatOCREnhancementConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool enabled = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatOCREnhancementConfiguration(enabled, serializedAdditionalRawData); + } + + 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(AzureChatOCREnhancementConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureChatOCREnhancementConfiguration 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 DeserializeAzureChatOCREnhancementConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatOCREnhancementConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatOCREnhancementConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureChatOCREnhancementConfiguration(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.cs new file mode 100644 index 000000000000..6f3aee5baa5a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. + public partial class AzureChatOCREnhancementConfiguration + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Specifies whether the enhancement is enabled. + public AzureChatOCREnhancementConfiguration(bool enabled) + { + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Specifies whether the enhancement is enabled. + /// Keeps track of any properties unknown to the library. + internal AzureChatOCREnhancementConfiguration(bool enabled, IDictionary serializedAdditionalRawData) + { + Enabled = enabled; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureChatOCREnhancementConfiguration() + { + } + + /// Specifies whether the enhancement is enabled. + public bool Enabled { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..b909db380846 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureCosmosDBChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureCosmosDBChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("parameters"u8); + writer.WriteObjectValue(Parameters, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureCosmosDBChatExtensionConfiguration 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(AzureCosmosDBChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureCosmosDBChatExtensionConfiguration(document.RootElement, options); + } + + internal static AzureCosmosDBChatExtensionConfiguration DeserializeAzureCosmosDBChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureCosmosDBChatExtensionParameters parameters = default; + AzureChatExtensionType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("parameters"u8)) + { + parameters = AzureCosmosDBChatExtensionParameters.DeserializeAzureCosmosDBChatExtensionParameters(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureCosmosDBChatExtensionConfiguration(type, serializedAdditionalRawData, parameters); + } + + 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(AzureCosmosDBChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureCosmosDBChatExtensionConfiguration 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 DeserializeAzureCosmosDBChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new AzureCosmosDBChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureCosmosDBChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.cs new file mode 100644 index 000000000000..c3b36d9749ea --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A specific representation of configurable options for Azure Cosmos DB when using it as an Azure OpenAI chat + /// extension. + /// + public partial class AzureCosmosDBChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// The parameters to use when configuring Azure OpenAI CosmosDB chat extensions. + /// is null. + public AzureCosmosDBChatExtensionConfiguration(AzureCosmosDBChatExtensionParameters parameters) + { + Argument.AssertNotNull(parameters, nameof(parameters)); + + Type = AzureChatExtensionType.AzureCosmosDB; + Parameters = parameters; + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + /// The parameters to use when configuring Azure OpenAI CosmosDB chat extensions. + internal AzureCosmosDBChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData, AzureCosmosDBChatExtensionParameters parameters) : base(type, serializedAdditionalRawData) + { + Parameters = parameters; + } + + /// Initializes a new instance of for deserialization. + internal AzureCosmosDBChatExtensionConfiguration() + { + } + + /// The parameters to use when configuring Azure OpenAI CosmosDB chat extensions. + public AzureCosmosDBChatExtensionParameters Parameters { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureCosmosDBChatDataSourceParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.Serialization.cs similarity index 54% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureCosmosDBChatDataSourceParameters.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.Serialization.cs index 677a0355da0b..5c999d2cac84 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureCosmosDBChatDataSourceParameters.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.Serialization.cs @@ -1,99 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - internal partial class InternalAzureCosmosDBChatDataSourceParameters : IJsonModel + public partial class AzureCosmosDBChatExtensionParameters : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(InternalAzureCosmosDBChatDataSourceParameters)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionParameters)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("top_n_documents") != true && Optional.IsDefined(TopNDocuments)) + if (Optional.IsDefined(DocumentCount)) { writer.WritePropertyName("top_n_documents"u8); - writer.WriteNumberValue(TopNDocuments.Value); + writer.WriteNumberValue(DocumentCount.Value); } - if (SerializedAdditionalRawData?.ContainsKey("in_scope") != true && Optional.IsDefined(InScope)) + if (Optional.IsDefined(ShouldRestrictResultScope)) { writer.WritePropertyName("in_scope"u8); - writer.WriteBooleanValue(InScope.Value); + writer.WriteBooleanValue(ShouldRestrictResultScope.Value); } - if (SerializedAdditionalRawData?.ContainsKey("strictness") != true && Optional.IsDefined(Strictness)) + if (Optional.IsDefined(Strictness)) { writer.WritePropertyName("strictness"u8); writer.WriteNumberValue(Strictness.Value); } - if (SerializedAdditionalRawData?.ContainsKey("max_search_queries") != true && Optional.IsDefined(MaxSearchQueries)) + if (Optional.IsDefined(MaxSearchQueries)) { writer.WritePropertyName("max_search_queries"u8); writer.WriteNumberValue(MaxSearchQueries.Value); } - if (SerializedAdditionalRawData?.ContainsKey("allow_partial_result") != true && Optional.IsDefined(AllowPartialResult)) + if (Optional.IsDefined(AllowPartialResult)) { writer.WritePropertyName("allow_partial_result"u8); writer.WriteBooleanValue(AllowPartialResult.Value); } - if (SerializedAdditionalRawData?.ContainsKey("include_contexts") != true && Optional.IsCollectionDefined(_internalIncludeContexts)) + if (Optional.IsCollectionDefined(IncludeContexts)) { writer.WritePropertyName("include_contexts"u8); writer.WriteStartArray(); - foreach (var item in _internalIncludeContexts) + foreach (var item in IncludeContexts) { - writer.WriteStringValue(item); + writer.WriteStringValue(item.ToString()); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("container_name") != true) - { - writer.WritePropertyName("container_name"u8); - writer.WriteStringValue(ContainerName); - } - if (SerializedAdditionalRawData?.ContainsKey("database_name") != true) - { - writer.WritePropertyName("database_name"u8); - writer.WriteStringValue(DatabaseName); - } - if (SerializedAdditionalRawData?.ContainsKey("embedding_dependency") != true) - { - writer.WritePropertyName("embedding_dependency"u8); - writer.WriteObjectValue(VectorizationSource, options); - } - if (SerializedAdditionalRawData?.ContainsKey("index_name") != true) - { - writer.WritePropertyName("index_name"u8); - writer.WriteStringValue(IndexName); - } - if (SerializedAdditionalRawData?.ContainsKey("authentication") != true) + if (Optional.IsDefined(Authentication)) { writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); + writer.WriteObjectValue(Authentication, options); } - if (SerializedAdditionalRawData?.ContainsKey("fields_mapping") != true) + writer.WritePropertyName("database_name"u8); + writer.WriteStringValue(DatabaseName); + writer.WritePropertyName("container_name"u8); + writer.WriteStringValue(ContainerName); + writer.WritePropertyName("index_name"u8); + writer.WriteStringValue(IndexName); + writer.WritePropertyName("fields_mapping"u8); + writer.WriteObjectValue(FieldMappingOptions, options); + writer.WritePropertyName("embedding_dependency"u8); + writer.WriteObjectValue(EmbeddingDependency, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) { - writer.WritePropertyName("fields_mapping"u8); - writer.WriteObjectValue(FieldMappings, options); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -108,19 +94,19 @@ void IJsonModel.Write(Utf8JsonWri writer.WriteEndObject(); } - InternalAzureCosmosDBChatDataSourceParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AzureCosmosDBChatExtensionParameters 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(InternalAzureCosmosDBChatDataSourceParameters)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionParameters)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureCosmosDBChatDataSourceParameters(document.RootElement, options); + return DeserializeAzureCosmosDBChatExtensionParameters(document.RootElement, options); } - internal static InternalAzureCosmosDBChatDataSourceParameters DeserializeInternalAzureCosmosDBChatDataSourceParameters(JsonElement element, ModelReaderWriterOptions options = null) + internal static AzureCosmosDBChatExtensionParameters DeserializeAzureCosmosDBChatExtensionParameters(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -133,13 +119,13 @@ internal static InternalAzureCosmosDBChatDataSourceParameters DeserializeInterna int? strictness = default; int? maxSearchQueries = default; bool? allowPartialResult = default; - IList includeContexts = default; - string containerName = default; + IList includeContexts = default; + OnYourDataAuthenticationOptions authentication = default; string databaseName = default; - DataSourceVectorizer embeddingDependency = default; + string containerName = default; string indexName = default; - DataSourceAuthentication authentication = default; - DataSourceFieldMappings fieldsMapping = default; + AzureCosmosDBFieldMappingOptions fieldsMapping = default; + OnYourDataVectorizationSource embeddingDependency = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -195,17 +181,21 @@ internal static InternalAzureCosmosDBChatDataSourceParameters DeserializeInterna { continue; } - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(item.GetString()); + array.Add(new OnYourDataContextProperty(item.GetString())); } includeContexts = array; continue; } - if (property.NameEquals("container_name"u8)) + if (property.NameEquals("authentication"u8)) { - containerName = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + authentication = OnYourDataAuthenticationOptions.DeserializeOnYourDataAuthenticationOptions(property.Value, options); continue; } if (property.NameEquals("database_name"u8)) @@ -213,9 +203,9 @@ internal static InternalAzureCosmosDBChatDataSourceParameters DeserializeInterna databaseName = property.Value.GetString(); continue; } - if (property.NameEquals("embedding_dependency"u8)) + if (property.NameEquals("container_name"u8)) { - embeddingDependency = DataSourceVectorizer.DeserializeDataSourceVectorizer(property.Value, options); + containerName = property.Value.GetString(); continue; } if (property.NameEquals("index_name"u8)) @@ -223,83 +213,83 @@ internal static InternalAzureCosmosDBChatDataSourceParameters DeserializeInterna indexName = property.Value.GetString(); continue; } - if (property.NameEquals("authentication"u8)) + if (property.NameEquals("fields_mapping"u8)) { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(property.Value, options); + fieldsMapping = AzureCosmosDBFieldMappingOptions.DeserializeAzureCosmosDBFieldMappingOptions(property.Value, options); continue; } - if (property.NameEquals("fields_mapping"u8)) + if (property.NameEquals("embedding_dependency"u8)) { - fieldsMapping = DataSourceFieldMappings.DeserializeDataSourceFieldMappings(property.Value, options); + embeddingDependency = OnYourDataVectorizationSource.DeserializeOnYourDataVectorizationSource(property.Value, options); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureCosmosDBChatDataSourceParameters( + return new AzureCosmosDBChatExtensionParameters( topNDocuments, inScope, strictness, maxSearchQueries, allowPartialResult, - includeContexts ?? new ChangeTrackingList(), - containerName, + includeContexts ?? new ChangeTrackingList(), + authentication, databaseName, - embeddingDependency, + containerName, indexName, - authentication, fieldsMapping, + embeddingDependency, 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(InternalAzureCosmosDBChatDataSourceParameters)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionParameters)} does not support writing '{options.Format}' format."); } } - InternalAzureCosmosDBChatDataSourceParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + AzureCosmosDBChatExtensionParameters 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 DeserializeInternalAzureCosmosDBChatDataSourceParameters(document.RootElement, options); + return DeserializeAzureCosmosDBChatExtensionParameters(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalAzureCosmosDBChatDataSourceParameters)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionParameters)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalAzureCosmosDBChatDataSourceParameters FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static AzureCosmosDBChatExtensionParameters FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureCosmosDBChatDataSourceParameters(document.RootElement); + return DeserializeAzureCosmosDBChatExtensionParameters(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.cs new file mode 100644 index 000000000000..af4079791b60 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// Parameters to use when configuring Azure OpenAI On Your Data chat extensions when using Azure Cosmos DB for + /// MongoDB vCore. The supported authentication type is ConnectionString. + /// + public partial class AzureCosmosDBChatExtensionParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The MongoDB vCore database name to use with Azure Cosmos DB. + /// The name of the Azure Cosmos DB resource container. + /// The MongoDB vCore index name to use with Azure Cosmos DB. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// , , , or is null. + public AzureCosmosDBChatExtensionParameters(string databaseName, string containerName, string indexName, AzureCosmosDBFieldMappingOptions fieldMappingOptions, OnYourDataVectorizationSource embeddingDependency) + { + Argument.AssertNotNull(databaseName, nameof(databaseName)); + Argument.AssertNotNull(containerName, nameof(containerName)); + Argument.AssertNotNull(indexName, nameof(indexName)); + Argument.AssertNotNull(fieldMappingOptions, nameof(fieldMappingOptions)); + Argument.AssertNotNull(embeddingDependency, nameof(embeddingDependency)); + + IncludeContexts = new ChangeTrackingList(); + DatabaseName = databaseName; + ContainerName = containerName; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + EmbeddingDependency = embeddingDependency; + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The MongoDB vCore database name to use with Azure Cosmos DB. + /// The name of the Azure Cosmos DB resource container. + /// The MongoDB vCore index name to use with Azure Cosmos DB. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// Keeps track of any properties unknown to the library. + internal AzureCosmosDBChatExtensionParameters(int? documentCount, bool? shouldRestrictResultScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList includeContexts, OnYourDataAuthenticationOptions authentication, string databaseName, string containerName, string indexName, AzureCosmosDBFieldMappingOptions fieldMappingOptions, OnYourDataVectorizationSource embeddingDependency, IDictionary serializedAdditionalRawData) + { + DocumentCount = documentCount; + ShouldRestrictResultScope = shouldRestrictResultScope; + Strictness = strictness; + MaxSearchQueries = maxSearchQueries; + AllowPartialResult = allowPartialResult; + IncludeContexts = includeContexts; + Authentication = authentication; + DatabaseName = databaseName; + ContainerName = containerName; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + EmbeddingDependency = embeddingDependency; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureCosmosDBChatExtensionParameters() + { + } + + /// The configured top number of documents to feature for the configured query. + public int? DocumentCount { get; set; } + /// Whether queries should be restricted to use of indexed data. + public bool? ShouldRestrictResultScope { get; set; } + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + public int? Strictness { get; set; } + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + public int? MaxSearchQueries { get; set; } + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + public bool? AllowPartialResult { get; set; } + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + public IList IncludeContexts { get; } + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + public OnYourDataAuthenticationOptions Authentication { get; set; } + /// The MongoDB vCore database name to use with Azure Cosmos DB. + public string DatabaseName { get; } + /// The name of the Azure Cosmos DB resource container. + public string ContainerName { get; } + /// The MongoDB vCore index name to use with Azure Cosmos DB. + public string IndexName { get; } + /// Customized field mapping behavior to use when interacting with the search index. + public AzureCosmosDBFieldMappingOptions FieldMappingOptions { get; } + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public OnYourDataVectorizationSource EmbeddingDependency { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.Serialization.cs new file mode 100644 index 000000000000..462a964dd0b2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.Serialization.cs @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureCosmosDBFieldMappingOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureCosmosDBFieldMappingOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(TitleFieldName)) + { + writer.WritePropertyName("title_field"u8); + writer.WriteStringValue(TitleFieldName); + } + if (Optional.IsDefined(UrlFieldName)) + { + writer.WritePropertyName("url_field"u8); + writer.WriteStringValue(UrlFieldName); + } + if (Optional.IsDefined(FilepathFieldName)) + { + writer.WritePropertyName("filepath_field"u8); + writer.WriteStringValue(FilepathFieldName); + } + writer.WritePropertyName("content_fields"u8); + writer.WriteStartArray(); + foreach (var item in ContentFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(ContentFieldSeparator)) + { + writer.WritePropertyName("content_fields_separator"u8); + writer.WriteStringValue(ContentFieldSeparator); + } + writer.WritePropertyName("vector_fields"u8); + writer.WriteStartArray(); + foreach (var item in VectorFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureCosmosDBFieldMappingOptions 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(AzureCosmosDBFieldMappingOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureCosmosDBFieldMappingOptions(document.RootElement, options); + } + + internal static AzureCosmosDBFieldMappingOptions DeserializeAzureCosmosDBFieldMappingOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string titleField = default; + string urlField = default; + string filepathField = default; + IList contentFields = default; + string contentFieldsSeparator = default; + IList vectorFields = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("title_field"u8)) + { + titleField = property.Value.GetString(); + continue; + } + if (property.NameEquals("url_field"u8)) + { + urlField = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath_field"u8)) + { + filepathField = property.Value.GetString(); + continue; + } + if (property.NameEquals("content_fields"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + contentFields = array; + continue; + } + if (property.NameEquals("content_fields_separator"u8)) + { + contentFieldsSeparator = property.Value.GetString(); + continue; + } + if (property.NameEquals("vector_fields"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorFields = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureCosmosDBFieldMappingOptions( + titleField, + urlField, + filepathField, + contentFields, + contentFieldsSeparator, + vectorFields, + serializedAdditionalRawData); + } + + 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(AzureCosmosDBFieldMappingOptions)} does not support writing '{options.Format}' format."); + } + } + + AzureCosmosDBFieldMappingOptions 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 DeserializeAzureCosmosDBFieldMappingOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureCosmosDBFieldMappingOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureCosmosDBFieldMappingOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureCosmosDBFieldMappingOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.cs new file mode 100644 index 000000000000..aff56c9de289 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Optional settings to control how fields are processed when using a configured Azure Cosmos DB resource. + public partial class AzureCosmosDBFieldMappingOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The names of index fields that should be treated as content. + /// The names of fields that represent vector data. + /// or is null. + public AzureCosmosDBFieldMappingOptions(IEnumerable contentFieldNames, IEnumerable vectorFieldNames) + { + Argument.AssertNotNull(contentFieldNames, nameof(contentFieldNames)); + Argument.AssertNotNull(vectorFieldNames, nameof(vectorFieldNames)); + + ContentFieldNames = contentFieldNames.ToList(); + VectorFieldNames = vectorFieldNames.ToList(); + } + + /// Initializes a new instance of . + /// The name of the index field to use as a title. + /// The name of the index field to use as a URL. + /// The name of the index field to use as a filepath. + /// The names of index fields that should be treated as content. + /// The separator pattern that content fields should use. + /// The names of fields that represent vector data. + /// Keeps track of any properties unknown to the library. + internal AzureCosmosDBFieldMappingOptions(string titleFieldName, string urlFieldName, string filepathFieldName, IList contentFieldNames, string contentFieldSeparator, IList vectorFieldNames, IDictionary serializedAdditionalRawData) + { + TitleFieldName = titleFieldName; + UrlFieldName = urlFieldName; + FilepathFieldName = filepathFieldName; + ContentFieldNames = contentFieldNames; + ContentFieldSeparator = contentFieldSeparator; + VectorFieldNames = vectorFieldNames; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureCosmosDBFieldMappingOptions() + { + } + + /// The name of the index field to use as a title. + public string TitleFieldName { get; set; } + /// The name of the index field to use as a URL. + public string UrlFieldName { get; set; } + /// The name of the index field to use as a filepath. + public string FilepathFieldName { get; set; } + /// The names of index fields that should be treated as content. + public IList ContentFieldNames { get; } + /// The separator pattern that content fields should use. + public string ContentFieldSeparator { get; set; } + /// The names of fields that represent vector data. + public IList VectorFieldNames { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.Serialization.cs new file mode 100644 index 000000000000..204ed5ac7a3a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.Serialization.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureGroundingEnhancement : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureGroundingEnhancement)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("lines"u8); + writer.WriteStartArray(); + foreach (var item in Lines) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureGroundingEnhancement 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(AzureGroundingEnhancement)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureGroundingEnhancement(document.RootElement, options); + } + + internal static AzureGroundingEnhancement DeserializeAzureGroundingEnhancement(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList lines = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("lines"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureGroundingEnhancementLine.DeserializeAzureGroundingEnhancementLine(item, options)); + } + lines = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureGroundingEnhancement(lines, serializedAdditionalRawData); + } + + 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(AzureGroundingEnhancement)} does not support writing '{options.Format}' format."); + } + } + + AzureGroundingEnhancement 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 DeserializeAzureGroundingEnhancement(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancement)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureGroundingEnhancement FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureGroundingEnhancement(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.cs new file mode 100644 index 000000000000..c0194b3dfa44 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The grounding enhancement that returns the bounding box of the objects detected in the image. + public partial class AzureGroundingEnhancement + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The lines of text detected by the grounding enhancement. + /// is null. + internal AzureGroundingEnhancement(IEnumerable lines) + { + Argument.AssertNotNull(lines, nameof(lines)); + + Lines = lines.ToList(); + } + + /// Initializes a new instance of . + /// The lines of text detected by the grounding enhancement. + /// Keeps track of any properties unknown to the library. + internal AzureGroundingEnhancement(IReadOnlyList lines, IDictionary serializedAdditionalRawData) + { + Lines = lines; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureGroundingEnhancement() + { + } + + /// The lines of text detected by the grounding enhancement. + public IReadOnlyList Lines { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.Serialization.cs new file mode 100644 index 000000000000..e4ef867aaff2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureGroundingEnhancementCoordinatePoint : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureGroundingEnhancementCoordinatePoint)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("x"u8); + writer.WriteNumberValue(X); + writer.WritePropertyName("y"u8); + writer.WriteNumberValue(Y); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureGroundingEnhancementCoordinatePoint 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(AzureGroundingEnhancementCoordinatePoint)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureGroundingEnhancementCoordinatePoint(document.RootElement, options); + } + + internal static AzureGroundingEnhancementCoordinatePoint DeserializeAzureGroundingEnhancementCoordinatePoint(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + float x = default; + float y = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("x"u8)) + { + x = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("y"u8)) + { + y = property.Value.GetSingle(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureGroundingEnhancementCoordinatePoint(x, y, serializedAdditionalRawData); + } + + 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(AzureGroundingEnhancementCoordinatePoint)} does not support writing '{options.Format}' format."); + } + } + + AzureGroundingEnhancementCoordinatePoint 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 DeserializeAzureGroundingEnhancementCoordinatePoint(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancementCoordinatePoint)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureGroundingEnhancementCoordinatePoint FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureGroundingEnhancementCoordinatePoint(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.cs new file mode 100644 index 000000000000..44b5c9dcbd18 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of a single polygon point as used by the Azure grounding enhancement. + public partial class AzureGroundingEnhancementCoordinatePoint + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The x-coordinate (horizontal axis) of the point. + /// The y-coordinate (vertical axis) of the point. + internal AzureGroundingEnhancementCoordinatePoint(float x, float y) + { + X = x; + Y = y; + } + + /// Initializes a new instance of . + /// The x-coordinate (horizontal axis) of the point. + /// The y-coordinate (vertical axis) of the point. + /// Keeps track of any properties unknown to the library. + internal AzureGroundingEnhancementCoordinatePoint(float x, float y, IDictionary serializedAdditionalRawData) + { + X = x; + Y = y; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureGroundingEnhancementCoordinatePoint() + { + } + + /// The x-coordinate (horizontal axis) of the point. + public float X { get; } + /// The y-coordinate (vertical axis) of the point. + public float Y { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.Serialization.cs new file mode 100644 index 000000000000..51b343d861fc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureGroundingEnhancementLine : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureGroundingEnhancementLine)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("spans"u8); + writer.WriteStartArray(); + foreach (var item in Spans) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureGroundingEnhancementLine 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(AzureGroundingEnhancementLine)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureGroundingEnhancementLine(document.RootElement, options); + } + + internal static AzureGroundingEnhancementLine DeserializeAzureGroundingEnhancementLine(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + IReadOnlyList spans = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("spans"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureGroundingEnhancementLineSpan.DeserializeAzureGroundingEnhancementLineSpan(item, options)); + } + spans = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureGroundingEnhancementLine(text, spans, serializedAdditionalRawData); + } + + 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(AzureGroundingEnhancementLine)} does not support writing '{options.Format}' format."); + } + } + + AzureGroundingEnhancementLine 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 DeserializeAzureGroundingEnhancementLine(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancementLine)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureGroundingEnhancementLine FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureGroundingEnhancementLine(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.cs new file mode 100644 index 000000000000..5ce268709106 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// A content line object consisting of an adjacent sequence of content elements, such as words and selection marks. + public partial class AzureGroundingEnhancementLine + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The text within the line. + /// An array of spans that represent detected objects and its bounding box information. + /// or is null. + internal AzureGroundingEnhancementLine(string text, IEnumerable spans) + { + Argument.AssertNotNull(text, nameof(text)); + Argument.AssertNotNull(spans, nameof(spans)); + + Text = text; + Spans = spans.ToList(); + } + + /// Initializes a new instance of . + /// The text within the line. + /// An array of spans that represent detected objects and its bounding box information. + /// Keeps track of any properties unknown to the library. + internal AzureGroundingEnhancementLine(string text, IReadOnlyList spans, IDictionary serializedAdditionalRawData) + { + Text = text; + Spans = spans; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureGroundingEnhancementLine() + { + } + + /// The text within the line. + public string Text { get; } + /// An array of spans that represent detected objects and its bounding box information. + public IReadOnlyList Spans { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.Serialization.cs new file mode 100644 index 000000000000..a7db6c01a403 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.Serialization.cs @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureGroundingEnhancementLineSpan : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureGroundingEnhancementLineSpan)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("offset"u8); + writer.WriteNumberValue(Offset); + writer.WritePropertyName("length"u8); + writer.WriteNumberValue(Length); + writer.WritePropertyName("polygon"u8); + writer.WriteStartArray(); + foreach (var item in Polygon) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureGroundingEnhancementLineSpan 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(AzureGroundingEnhancementLineSpan)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureGroundingEnhancementLineSpan(document.RootElement, options); + } + + internal static AzureGroundingEnhancementLineSpan DeserializeAzureGroundingEnhancementLineSpan(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + int offset = default; + int length = default; + IReadOnlyList polygon = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("offset"u8)) + { + offset = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("length"u8)) + { + length = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("polygon"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureGroundingEnhancementCoordinatePoint.DeserializeAzureGroundingEnhancementCoordinatePoint(item, options)); + } + polygon = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureGroundingEnhancementLineSpan(text, offset, length, polygon, serializedAdditionalRawData); + } + + 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(AzureGroundingEnhancementLineSpan)} does not support writing '{options.Format}' format."); + } + } + + AzureGroundingEnhancementLineSpan 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 DeserializeAzureGroundingEnhancementLineSpan(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancementLineSpan)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureGroundingEnhancementLineSpan FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureGroundingEnhancementLineSpan(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.cs new file mode 100644 index 000000000000..0c370dd4d762 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// A span object that represents a detected object and its bounding box information. + public partial class AzureGroundingEnhancementLineSpan + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The text content of the span that represents the detected object. + /// + /// The character offset within the text where the span begins. This offset is defined as the position of the first + /// character of the span, counting from the start of the text as Unicode codepoints. + /// + /// The length of the span in characters, measured in Unicode codepoints. + /// An array of objects representing points in the polygon that encloses the detected object. + /// or is null. + internal AzureGroundingEnhancementLineSpan(string text, int offset, int length, IEnumerable polygon) + { + Argument.AssertNotNull(text, nameof(text)); + Argument.AssertNotNull(polygon, nameof(polygon)); + + Text = text; + Offset = offset; + Length = length; + Polygon = polygon.ToList(); + } + + /// Initializes a new instance of . + /// The text content of the span that represents the detected object. + /// + /// The character offset within the text where the span begins. This offset is defined as the position of the first + /// character of the span, counting from the start of the text as Unicode codepoints. + /// + /// The length of the span in characters, measured in Unicode codepoints. + /// An array of objects representing points in the polygon that encloses the detected object. + /// Keeps track of any properties unknown to the library. + internal AzureGroundingEnhancementLineSpan(string text, int offset, int length, IReadOnlyList polygon, IDictionary serializedAdditionalRawData) + { + Text = text; + Offset = offset; + Length = length; + Polygon = polygon; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureGroundingEnhancementLineSpan() + { + } + + /// The text content of the span that represents the detected object. + public string Text { get; } + /// + /// The character offset within the text where the span begins. This offset is defined as the position of the first + /// character of the span, counting from the start of the text as Unicode codepoints. + /// + public int Offset { get; } + /// The length of the span in characters, measured in Unicode codepoints. + public int Length { get; } + /// An array of objects representing points in the polygon that encloses the detected object. + public IReadOnlyList Polygon { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatError.Serialization.cs deleted file mode 100644 index d4bda9baa41c..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatError.Serialization.cs +++ /dev/null @@ -1,190 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIChatError : 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(AzureOpenAIChatError)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true && Optional.IsDefined(Code)) - { - writer.WritePropertyName("code"u8); - writer.WriteStringValue(Code); - } - if (SerializedAdditionalRawData?.ContainsKey("message") != true && Optional.IsDefined(Message)) - { - writer.WritePropertyName("message"u8); - writer.WriteStringValue(Message); - } - if (SerializedAdditionalRawData?.ContainsKey("param") != true && Optional.IsDefined(Param)) - { - writer.WritePropertyName("param"u8); - writer.WriteStringValue(Param); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true && Optional.IsDefined(Type)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData?.ContainsKey("inner_error") != true && Optional.IsDefined(InnerError)) - { - writer.WritePropertyName("inner_error"u8); - writer.WriteObjectValue(InnerError, 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(); - } - - AzureOpenAIChatError 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(AzureOpenAIChatError)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureOpenAIChatError(document.RootElement, options); - } - - internal static AzureOpenAIChatError DeserializeAzureOpenAIChatError(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string code = default; - string message = default; - string param = default; - string type = default; - InternalAzureOpenAIChatErrorInnerError innerError = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("code"u8)) - { - code = property.Value.GetString(); - continue; - } - if (property.NameEquals("message"u8)) - { - message = property.Value.GetString(); - continue; - } - if (property.NameEquals("param"u8)) - { - param = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (property.NameEquals("inner_error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - innerError = InternalAzureOpenAIChatErrorInnerError.DeserializeInternalAzureOpenAIChatErrorInnerError(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new AzureOpenAIChatError( - code, - message, - param, - type, - innerError, - serializedAdditionalRawData); - } - - 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(AzureOpenAIChatError)} does not support writing '{options.Format}' format."); - } - } - - AzureOpenAIChatError 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 DeserializeAzureOpenAIChatError(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureOpenAIChatError)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static AzureOpenAIChatError FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAzureOpenAIChatError(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatError.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatError.cs deleted file mode 100644 index b379c88ac0a8..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatError.cs +++ /dev/null @@ -1,77 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// The structured representation of an error from an Azure OpenAI chat completion request. - internal partial class AzureOpenAIChatError - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal AzureOpenAIChatError() - { - } - - /// Initializes a new instance of . - /// The distinct, machine-generated identifier for the error. - /// A human-readable message associated with the error. - /// If applicable, the request input parameter associated with the error. - /// If applicable, the input line number associated with the error. - /// If applicable, an upstream error that originated this error. - /// Keeps track of any properties unknown to the library. - internal AzureOpenAIChatError(string code, string message, string param, string type, InternalAzureOpenAIChatErrorInnerError innerError, IDictionary serializedAdditionalRawData) - { - Code = code; - Message = message; - Param = param; - Type = type; - InnerError = innerError; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The distinct, machine-generated identifier for the error. - public string Code { get; } - /// A human-readable message associated with the error. - public string Message { get; } - /// If applicable, the request input parameter associated with the error. - public string Param { get; } - /// If applicable, the input line number associated with the error. - public string Type { get; } - /// If applicable, an upstream error that originated this error. - public InternalAzureOpenAIChatErrorInnerError InnerError { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatErrorResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatErrorResponse.Serialization.cs deleted file mode 100644 index a85c386fd313..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIChatErrorResponse.Serialization.cs +++ /dev/null @@ -1,140 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIChatErrorResponse : 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(AzureOpenAIChatErrorResponse)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("error") != true && Optional.IsDefined(Error)) - { - writer.WritePropertyName("error"u8); - writer.WriteObjectValue(Error, 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(); - } - - AzureOpenAIChatErrorResponse 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(AzureOpenAIChatErrorResponse)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureOpenAIChatErrorResponse(document.RootElement, options); - } - - internal static AzureOpenAIChatErrorResponse DeserializeAzureOpenAIChatErrorResponse(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureOpenAIChatError error = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - error = AzureOpenAIChatError.DeserializeAzureOpenAIChatError(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new AzureOpenAIChatErrorResponse(error, serializedAdditionalRawData); - } - - 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(AzureOpenAIChatErrorResponse)} does not support writing '{options.Format}' format."); - } - } - - AzureOpenAIChatErrorResponse 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 DeserializeAzureOpenAIChatErrorResponse(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureOpenAIChatErrorResponse)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static AzureOpenAIChatErrorResponse FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAzureOpenAIChatErrorResponse(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleError.Serialization.cs deleted file mode 100644 index 2498a9dac44b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleError.Serialization.cs +++ /dev/null @@ -1,190 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIDalleError : 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(AzureOpenAIDalleError)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true && Optional.IsDefined(Code)) - { - writer.WritePropertyName("code"u8); - writer.WriteStringValue(Code); - } - if (SerializedAdditionalRawData?.ContainsKey("message") != true && Optional.IsDefined(Message)) - { - writer.WritePropertyName("message"u8); - writer.WriteStringValue(Message); - } - if (SerializedAdditionalRawData?.ContainsKey("param") != true && Optional.IsDefined(Param)) - { - writer.WritePropertyName("param"u8); - writer.WriteStringValue(Param); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true && Optional.IsDefined(Type)) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData?.ContainsKey("inner_error") != true && Optional.IsDefined(InnerError)) - { - writer.WritePropertyName("inner_error"u8); - writer.WriteObjectValue(InnerError, 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(); - } - - AzureOpenAIDalleError 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(AzureOpenAIDalleError)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureOpenAIDalleError(document.RootElement, options); - } - - internal static AzureOpenAIDalleError DeserializeAzureOpenAIDalleError(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string code = default; - string message = default; - string param = default; - string type = default; - InternalAzureOpenAIDalleErrorInnerError innerError = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("code"u8)) - { - code = property.Value.GetString(); - continue; - } - if (property.NameEquals("message"u8)) - { - message = property.Value.GetString(); - continue; - } - if (property.NameEquals("param"u8)) - { - param = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (property.NameEquals("inner_error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - innerError = InternalAzureOpenAIDalleErrorInnerError.DeserializeInternalAzureOpenAIDalleErrorInnerError(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new AzureOpenAIDalleError( - code, - message, - param, - type, - innerError, - serializedAdditionalRawData); - } - - 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(AzureOpenAIDalleError)} does not support writing '{options.Format}' format."); - } - } - - AzureOpenAIDalleError 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 DeserializeAzureOpenAIDalleError(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureOpenAIDalleError)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static AzureOpenAIDalleError FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAzureOpenAIDalleError(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleError.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleError.cs deleted file mode 100644 index 7dfb2de16f66..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleError.cs +++ /dev/null @@ -1,77 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// The structured representation of an error from an Azure OpenAI image generation request. - internal partial class AzureOpenAIDalleError - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal AzureOpenAIDalleError() - { - } - - /// Initializes a new instance of . - /// The distinct, machine-generated identifier for the error. - /// A human-readable message associated with the error. - /// If applicable, the request input parameter associated with the error. - /// If applicable, the input line number associated with the error. - /// If applicable, an upstream error that originated this error. - /// Keeps track of any properties unknown to the library. - internal AzureOpenAIDalleError(string code, string message, string param, string type, InternalAzureOpenAIDalleErrorInnerError innerError, IDictionary serializedAdditionalRawData) - { - Code = code; - Message = message; - Param = param; - Type = type; - InnerError = innerError; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The distinct, machine-generated identifier for the error. - public string Code { get; } - /// A human-readable message associated with the error. - public string Message { get; } - /// If applicable, the request input parameter associated with the error. - public string Param { get; } - /// If applicable, the input line number associated with the error. - public string Type { get; } - /// If applicable, an upstream error that originated this error. - public InternalAzureOpenAIDalleErrorInnerError InnerError { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleErrorResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleErrorResponse.Serialization.cs deleted file mode 100644 index cdcc8bc203a6..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureOpenAIDalleErrorResponse.Serialization.cs +++ /dev/null @@ -1,140 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIDalleErrorResponse : 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(AzureOpenAIDalleErrorResponse)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("error") != true && Optional.IsDefined(Error)) - { - writer.WritePropertyName("error"u8); - writer.WriteObjectValue(Error, 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(); - } - - AzureOpenAIDalleErrorResponse 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(AzureOpenAIDalleErrorResponse)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureOpenAIDalleErrorResponse(document.RootElement, options); - } - - internal static AzureOpenAIDalleErrorResponse DeserializeAzureOpenAIDalleErrorResponse(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureOpenAIDalleError error = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("error"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - error = AzureOpenAIDalleError.DeserializeAzureOpenAIDalleError(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new AzureOpenAIDalleErrorResponse(error, serializedAdditionalRawData); - } - - 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(AzureOpenAIDalleErrorResponse)} does not support writing '{options.Format}' format."); - } - } - - AzureOpenAIDalleErrorResponse 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 DeserializeAzureOpenAIDalleErrorResponse(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureOpenAIDalleErrorResponse)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static AzureOpenAIDalleErrorResponse FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAzureOpenAIDalleErrorResponse(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatDataSource.Serialization.cs deleted file mode 100644 index a9deddec3d6a..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatDataSource.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - public partial class AzureSearchChatDataSource : 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(AzureSearchChatDataSource)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("parameters") != true) - { - writer.WritePropertyName("parameters"u8); - writer.WriteObjectValue(InternalParameters, options); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - AzureSearchChatDataSource 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(AzureSearchChatDataSource)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureSearchChatDataSource(document.RootElement, options); - } - - internal static AzureSearchChatDataSource DeserializeAzureSearchChatDataSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - InternalAzureSearchChatDataSourceParameters parameters = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("parameters"u8)) - { - parameters = InternalAzureSearchChatDataSourceParameters.DeserializeInternalAzureSearchChatDataSourceParameters(property.Value, options); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new AzureSearchChatDataSource(type, serializedAdditionalRawData, parameters); - } - - 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(AzureSearchChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - AzureSearchChatDataSource 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 DeserializeAzureSearchChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureSearchChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new AzureSearchChatDataSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeAzureSearchChatDataSource(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatDataSource.cs deleted file mode 100644 index 417a6abd7220..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatDataSource.cs +++ /dev/null @@ -1,14 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// Represents a data source configuration that will use an Azure Search resource. - public partial class AzureSearchChatDataSource : ChatDataSource - { - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..546f78ce3966 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureSearchChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureSearchChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("parameters"u8); + writer.WriteObjectValue(Parameters, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureSearchChatExtensionConfiguration 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(AzureSearchChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureSearchChatExtensionConfiguration(document.RootElement, options); + } + + internal static AzureSearchChatExtensionConfiguration DeserializeAzureSearchChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureSearchChatExtensionParameters parameters = default; + AzureChatExtensionType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("parameters"u8)) + { + parameters = AzureSearchChatExtensionParameters.DeserializeAzureSearchChatExtensionParameters(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureSearchChatExtensionConfiguration(type, serializedAdditionalRawData, parameters); + } + + 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(AzureSearchChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureSearchChatExtensionConfiguration 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 DeserializeAzureSearchChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureSearchChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new AzureSearchChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeAzureSearchChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.cs new file mode 100644 index 000000000000..5123cfe7c574 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A specific representation of configurable options for Azure Search when using it as an Azure OpenAI chat + /// extension. + /// + public partial class AzureSearchChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// The parameters to use when configuring Azure Search. + /// is null. + public AzureSearchChatExtensionConfiguration(AzureSearchChatExtensionParameters parameters) + { + Argument.AssertNotNull(parameters, nameof(parameters)); + + Type = AzureChatExtensionType.AzureSearch; + Parameters = parameters; + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + /// The parameters to use when configuring Azure Search. + internal AzureSearchChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData, AzureSearchChatExtensionParameters parameters) : base(type, serializedAdditionalRawData) + { + Parameters = parameters; + } + + /// Initializes a new instance of for deserialization. + internal AzureSearchChatExtensionConfiguration() + { + } + + /// The parameters to use when configuring Azure Search. + public AzureSearchChatExtensionParameters Parameters { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureSearchChatDataSourceParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.Serialization.cs similarity index 58% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureSearchChatDataSourceParameters.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.Serialization.cs index 49694aa0a5ec..25c7ae3fa091 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureSearchChatDataSourceParameters.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.Serialization.cs @@ -1,109 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - internal partial class InternalAzureSearchChatDataSourceParameters : IJsonModel + public partial class AzureSearchChatExtensionParameters : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(InternalAzureSearchChatDataSourceParameters)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(AzureSearchChatExtensionParameters)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("top_n_documents") != true && Optional.IsDefined(TopNDocuments)) + if (Optional.IsDefined(DocumentCount)) { writer.WritePropertyName("top_n_documents"u8); - writer.WriteNumberValue(TopNDocuments.Value); + writer.WriteNumberValue(DocumentCount.Value); } - if (SerializedAdditionalRawData?.ContainsKey("in_scope") != true && Optional.IsDefined(InScope)) + if (Optional.IsDefined(ShouldRestrictResultScope)) { writer.WritePropertyName("in_scope"u8); - writer.WriteBooleanValue(InScope.Value); + writer.WriteBooleanValue(ShouldRestrictResultScope.Value); } - if (SerializedAdditionalRawData?.ContainsKey("strictness") != true && Optional.IsDefined(Strictness)) + if (Optional.IsDefined(Strictness)) { writer.WritePropertyName("strictness"u8); writer.WriteNumberValue(Strictness.Value); } - if (SerializedAdditionalRawData?.ContainsKey("max_search_queries") != true && Optional.IsDefined(MaxSearchQueries)) + if (Optional.IsDefined(MaxSearchQueries)) { writer.WritePropertyName("max_search_queries"u8); writer.WriteNumberValue(MaxSearchQueries.Value); } - if (SerializedAdditionalRawData?.ContainsKey("allow_partial_result") != true && Optional.IsDefined(AllowPartialResult)) + if (Optional.IsDefined(AllowPartialResult)) { writer.WritePropertyName("allow_partial_result"u8); writer.WriteBooleanValue(AllowPartialResult.Value); } - if (SerializedAdditionalRawData?.ContainsKey("include_contexts") != true && Optional.IsCollectionDefined(_internalIncludeContexts)) + if (Optional.IsCollectionDefined(IncludeContexts)) { writer.WritePropertyName("include_contexts"u8); writer.WriteStartArray(); - foreach (var item in _internalIncludeContexts) + foreach (var item in IncludeContexts) { - writer.WriteStringValue(item); + writer.WriteStringValue(item.ToString()); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("endpoint") != true) - { - writer.WritePropertyName("endpoint"u8); - writer.WriteStringValue(Endpoint.AbsoluteUri); - } - if (SerializedAdditionalRawData?.ContainsKey("index_name") != true) - { - writer.WritePropertyName("index_name"u8); - writer.WriteStringValue(IndexName); - } - if (SerializedAdditionalRawData?.ContainsKey("authentication") != true) + if (Optional.IsDefined(Authentication)) { writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); + writer.WriteObjectValue(Authentication, options); } - if (SerializedAdditionalRawData?.ContainsKey("fields_mapping") != true && Optional.IsDefined(FieldMappings)) + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(SearchEndpoint.AbsoluteUri); + writer.WritePropertyName("index_name"u8); + writer.WriteStringValue(IndexName); + if (Optional.IsDefined(FieldMappingOptions)) { writer.WritePropertyName("fields_mapping"u8); - writer.WriteObjectValue(FieldMappings, options); + writer.WriteObjectValue(FieldMappingOptions, options); } - if (SerializedAdditionalRawData?.ContainsKey("query_type") != true && Optional.IsDefined(QueryType)) + if (Optional.IsDefined(QueryType)) { writer.WritePropertyName("query_type"u8); writer.WriteStringValue(QueryType.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("semantic_configuration") != true && Optional.IsDefined(SemanticConfiguration)) + if (Optional.IsDefined(SemanticConfiguration)) { writer.WritePropertyName("semantic_configuration"u8); writer.WriteStringValue(SemanticConfiguration); } - if (SerializedAdditionalRawData?.ContainsKey("filter") != true && Optional.IsDefined(Filter)) + if (Optional.IsDefined(Filter)) { writer.WritePropertyName("filter"u8); writer.WriteStringValue(Filter); } - if (SerializedAdditionalRawData?.ContainsKey("embedding_dependency") != true && Optional.IsDefined(VectorizationSource)) + if (Optional.IsDefined(EmbeddingDependency)) { writer.WritePropertyName("embedding_dependency"u8); - writer.WriteObjectValue(VectorizationSource, options); + writer.WriteObjectValue(EmbeddingDependency, options); } - if (SerializedAdditionalRawData != null) + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -118,19 +113,19 @@ void IJsonModel.Write(Utf8JsonWrite writer.WriteEndObject(); } - InternalAzureSearchChatDataSourceParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AzureSearchChatExtensionParameters 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(InternalAzureSearchChatDataSourceParameters)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(AzureSearchChatExtensionParameters)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureSearchChatDataSourceParameters(document.RootElement, options); + return DeserializeAzureSearchChatExtensionParameters(document.RootElement, options); } - internal static InternalAzureSearchChatDataSourceParameters DeserializeInternalAzureSearchChatDataSourceParameters(JsonElement element, ModelReaderWriterOptions options = null) + internal static AzureSearchChatExtensionParameters DeserializeAzureSearchChatExtensionParameters(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -143,15 +138,15 @@ internal static InternalAzureSearchChatDataSourceParameters DeserializeInternalA int? strictness = default; int? maxSearchQueries = default; bool? allowPartialResult = default; - IList includeContexts = default; + IList includeContexts = default; + OnYourDataAuthenticationOptions authentication = default; Uri endpoint = default; string indexName = default; - DataSourceAuthentication authentication = default; - DataSourceFieldMappings fieldsMapping = default; - DataSourceQueryType? queryType = default; + AzureSearchIndexFieldMappingOptions fieldsMapping = default; + AzureSearchQueryType? queryType = default; string semanticConfiguration = default; string filter = default; - DataSourceVectorizer embeddingDependency = default; + OnYourDataVectorizationSource embeddingDependency = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -207,14 +202,23 @@ internal static InternalAzureSearchChatDataSourceParameters DeserializeInternalA { continue; } - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(item.GetString()); + array.Add(new OnYourDataContextProperty(item.GetString())); } includeContexts = array; continue; } + if (property.NameEquals("authentication"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + authentication = OnYourDataAuthenticationOptions.DeserializeOnYourDataAuthenticationOptions(property.Value, options); + continue; + } if (property.NameEquals("endpoint"u8)) { endpoint = new Uri(property.Value.GetString()); @@ -225,18 +229,13 @@ internal static InternalAzureSearchChatDataSourceParameters DeserializeInternalA indexName = property.Value.GetString(); continue; } - if (property.NameEquals("authentication"u8)) - { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(property.Value, options); - continue; - } if (property.NameEquals("fields_mapping"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - fieldsMapping = DataSourceFieldMappings.DeserializeDataSourceFieldMappings(property.Value, options); + fieldsMapping = AzureSearchIndexFieldMappingOptions.DeserializeAzureSearchIndexFieldMappingOptions(property.Value, options); continue; } if (property.NameEquals("query_type"u8)) @@ -245,7 +244,7 @@ internal static InternalAzureSearchChatDataSourceParameters DeserializeInternalA { continue; } - queryType = new DataSourceQueryType(property.Value.GetString()); + queryType = new AzureSearchQueryType(property.Value.GetString()); continue; } if (property.NameEquals("semantic_configuration"u8)) @@ -264,26 +263,25 @@ internal static InternalAzureSearchChatDataSourceParameters DeserializeInternalA { continue; } - embeddingDependency = DataSourceVectorizer.DeserializeDataSourceVectorizer(property.Value, options); + embeddingDependency = OnYourDataVectorizationSource.DeserializeOnYourDataVectorizationSource(property.Value, options); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureSearchChatDataSourceParameters( + return new AzureSearchChatExtensionParameters( topNDocuments, inScope, strictness, maxSearchQueries, allowPartialResult, - includeContexts ?? new ChangeTrackingList(), + includeContexts ?? new ChangeTrackingList(), + authentication, endpoint, indexName, - authentication, fieldsMapping, queryType, semanticConfiguration, @@ -292,50 +290,51 @@ internal static InternalAzureSearchChatDataSourceParameters DeserializeInternalA 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(InternalAzureSearchChatDataSourceParameters)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(AzureSearchChatExtensionParameters)} does not support writing '{options.Format}' format."); } } - InternalAzureSearchChatDataSourceParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + AzureSearchChatExtensionParameters 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 DeserializeInternalAzureSearchChatDataSourceParameters(document.RootElement, options); + return DeserializeAzureSearchChatExtensionParameters(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalAzureSearchChatDataSourceParameters)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(AzureSearchChatExtensionParameters)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalAzureSearchChatDataSourceParameters FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static AzureSearchChatExtensionParameters FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureSearchChatDataSourceParameters(document.RootElement); + return DeserializeAzureSearchChatExtensionParameters(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.cs new file mode 100644 index 000000000000..ad1430d18c2f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Parameters for Azure Cognitive Search when used as an Azure OpenAI chat extension. The supported authentication types are APIKey, SystemAssignedManagedIdentity and UserAssignedManagedIdentity. + public partial class AzureSearchChatExtensionParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The absolute endpoint path for the Azure Cognitive Search resource to use. + /// The name of the index to use as available in the referenced Azure Cognitive Search resource. + /// or is null. + public AzureSearchChatExtensionParameters(Uri searchEndpoint, string indexName) + { + Argument.AssertNotNull(searchEndpoint, nameof(searchEndpoint)); + Argument.AssertNotNull(indexName, nameof(indexName)); + + IncludeContexts = new ChangeTrackingList(); + SearchEndpoint = searchEndpoint; + IndexName = indexName; + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The absolute endpoint path for the Azure Cognitive Search resource to use. + /// The name of the index to use as available in the referenced Azure Cognitive Search resource. + /// Customized field mapping behavior to use when interacting with the search index. + /// The query type to use with Azure Cognitive Search. + /// The additional semantic configuration for the query. + /// Search filter. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// Keeps track of any properties unknown to the library. + internal AzureSearchChatExtensionParameters(int? documentCount, bool? shouldRestrictResultScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList includeContexts, OnYourDataAuthenticationOptions authentication, Uri searchEndpoint, string indexName, AzureSearchIndexFieldMappingOptions fieldMappingOptions, AzureSearchQueryType? queryType, string semanticConfiguration, string filter, OnYourDataVectorizationSource embeddingDependency, IDictionary serializedAdditionalRawData) + { + DocumentCount = documentCount; + ShouldRestrictResultScope = shouldRestrictResultScope; + Strictness = strictness; + MaxSearchQueries = maxSearchQueries; + AllowPartialResult = allowPartialResult; + IncludeContexts = includeContexts; + Authentication = authentication; + SearchEndpoint = searchEndpoint; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + QueryType = queryType; + SemanticConfiguration = semanticConfiguration; + Filter = filter; + EmbeddingDependency = embeddingDependency; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureSearchChatExtensionParameters() + { + } + + /// The configured top number of documents to feature for the configured query. + public int? DocumentCount { get; set; } + /// Whether queries should be restricted to use of indexed data. + public bool? ShouldRestrictResultScope { get; set; } + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + public int? Strictness { get; set; } + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + public int? MaxSearchQueries { get; set; } + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + public bool? AllowPartialResult { get; set; } + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + public IList IncludeContexts { get; } + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + public OnYourDataAuthenticationOptions Authentication { get; set; } + /// The absolute endpoint path for the Azure Cognitive Search resource to use. + public Uri SearchEndpoint { get; } + /// The name of the index to use as available in the referenced Azure Cognitive Search resource. + public string IndexName { get; } + /// Customized field mapping behavior to use when interacting with the search index. + public AzureSearchIndexFieldMappingOptions FieldMappingOptions { get; set; } + /// The query type to use with Azure Cognitive Search. + public AzureSearchQueryType? QueryType { get; set; } + /// The additional semantic configuration for the query. + public string SemanticConfiguration { get; set; } + /// Search filter. + public string Filter { get; set; } + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public OnYourDataVectorizationSource EmbeddingDependency { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceFieldMappings.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.Serialization.cs similarity index 66% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceFieldMappings.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.Serialization.cs index 9daa6c711873..920c9859bc18 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceFieldMappings.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.Serialization.cs @@ -1,42 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - public partial class DataSourceFieldMappings : IJsonModel + public partial class AzureSearchIndexFieldMappingOptions : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(DataSourceFieldMappings)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(AzureSearchIndexFieldMappingOptions)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("title_field") != true && Optional.IsDefined(TitleFieldName)) + if (Optional.IsDefined(TitleFieldName)) { writer.WritePropertyName("title_field"u8); writer.WriteStringValue(TitleFieldName); } - if (SerializedAdditionalRawData?.ContainsKey("url_field") != true && Optional.IsDefined(UrlFieldName)) + if (Optional.IsDefined(UrlFieldName)) { writer.WritePropertyName("url_field"u8); writer.WriteStringValue(UrlFieldName); } - if (SerializedAdditionalRawData?.ContainsKey("filepath_field") != true && Optional.IsDefined(FilePathFieldName)) + if (Optional.IsDefined(FilepathFieldName)) { writer.WritePropertyName("filepath_field"u8); - writer.WriteStringValue(FilePathFieldName); + writer.WriteStringValue(FilepathFieldName); } - if (SerializedAdditionalRawData?.ContainsKey("content_fields") != true && Optional.IsCollectionDefined(ContentFieldNames)) + if (Optional.IsCollectionDefined(ContentFieldNames)) { writer.WritePropertyName("content_fields"u8); writer.WriteStartArray(); @@ -46,12 +51,12 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("content_fields_separator") != true && Optional.IsDefined(ContentFieldSeparator)) + if (Optional.IsDefined(ContentFieldSeparator)) { writer.WritePropertyName("content_fields_separator"u8); writer.WriteStringValue(ContentFieldSeparator); } - if (SerializedAdditionalRawData?.ContainsKey("vector_fields") != true && Optional.IsCollectionDefined(VectorFieldNames)) + if (Optional.IsCollectionDefined(VectorFieldNames)) { writer.WritePropertyName("vector_fields"u8); writer.WriteStartArray(); @@ -61,7 +66,7 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("image_vector_fields") != true && Optional.IsCollectionDefined(ImageVectorFieldNames)) + if (Optional.IsCollectionDefined(ImageVectorFieldNames)) { writer.WritePropertyName("image_vector_fields"u8); writer.WriteStartArray(); @@ -71,14 +76,10 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -93,19 +94,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade writer.WriteEndObject(); } - DataSourceFieldMappings IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AzureSearchIndexFieldMappingOptions 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(DataSourceFieldMappings)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(AzureSearchIndexFieldMappingOptions)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataSourceFieldMappings(document.RootElement, options); + return DeserializeAzureSearchIndexFieldMappingOptions(document.RootElement, options); } - internal static DataSourceFieldMappings DeserializeDataSourceFieldMappings(JsonElement element, ModelReaderWriterOptions options = null) + internal static AzureSearchIndexFieldMappingOptions DeserializeAzureSearchIndexFieldMappingOptions(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -188,12 +189,11 @@ internal static DataSourceFieldMappings DeserializeDataSourceFieldMappings(JsonE } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new DataSourceFieldMappings( + return new AzureSearchIndexFieldMappingOptions( titleField, urlField, filepathField, @@ -204,49 +204,51 @@ internal static DataSourceFieldMappings DeserializeDataSourceFieldMappings(JsonE 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(DataSourceFieldMappings)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(AzureSearchIndexFieldMappingOptions)} does not support writing '{options.Format}' format."); } } - DataSourceFieldMappings IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + AzureSearchIndexFieldMappingOptions 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 DeserializeDataSourceFieldMappings(document.RootElement, options); + return DeserializeAzureSearchIndexFieldMappingOptions(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(DataSourceFieldMappings)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(AzureSearchIndexFieldMappingOptions)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static DataSourceFieldMappings FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static AzureSearchIndexFieldMappingOptions FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeDataSourceFieldMappings(document.RootElement); + return DeserializeAzureSearchIndexFieldMappingOptions(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.cs new file mode 100644 index 000000000000..cd659dda5d7f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Optional settings to control how fields are processed when using a configured Azure Search resource. + public partial class AzureSearchIndexFieldMappingOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public AzureSearchIndexFieldMappingOptions() + { + ContentFieldNames = new ChangeTrackingList(); + VectorFieldNames = new ChangeTrackingList(); + ImageVectorFieldNames = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The name of the index field to use as a title. + /// The name of the index field to use as a URL. + /// The name of the index field to use as a filepath. + /// The names of index fields that should be treated as content. + /// The separator pattern that content fields should use. + /// The names of fields that represent vector data. + /// The names of fields that represent image vector data. + /// Keeps track of any properties unknown to the library. + internal AzureSearchIndexFieldMappingOptions(string titleFieldName, string urlFieldName, string filepathFieldName, IList contentFieldNames, string contentFieldSeparator, IList vectorFieldNames, IList imageVectorFieldNames, IDictionary serializedAdditionalRawData) + { + TitleFieldName = titleFieldName; + UrlFieldName = urlFieldName; + FilepathFieldName = filepathFieldName; + ContentFieldNames = contentFieldNames; + ContentFieldSeparator = contentFieldSeparator; + VectorFieldNames = vectorFieldNames; + ImageVectorFieldNames = imageVectorFieldNames; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The name of the index field to use as a title. + public string TitleFieldName { get; set; } + /// The name of the index field to use as a URL. + public string UrlFieldName { get; set; } + /// The name of the index field to use as a filepath. + public string FilepathFieldName { get; set; } + /// The names of index fields that should be treated as content. + public IList ContentFieldNames { get; } + /// The separator pattern that content fields should use. + public string ContentFieldSeparator { get; set; } + /// The names of fields that represent vector data. + public IList VectorFieldNames { get; } + /// The names of fields that represent image vector data. + public IList ImageVectorFieldNames { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchQueryType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchQueryType.cs new file mode 100644 index 000000000000..98b220dec5f2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchQueryType.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The type of Azure Search retrieval query that should be executed when using it as an Azure OpenAI chat extension. + public readonly partial struct AzureSearchQueryType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AzureSearchQueryType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SimpleValue = "simple"; + private const string SemanticValue = "semantic"; + private const string VectorValue = "vector"; + private const string VectorSimpleHybridValue = "vector_simple_hybrid"; + private const string VectorSemanticHybridValue = "vector_semantic_hybrid"; + + /// Represents the default, simple query parser. + public static AzureSearchQueryType Simple { get; } = new AzureSearchQueryType(SimpleValue); + /// Represents the semantic query parser for advanced semantic modeling. + public static AzureSearchQueryType Semantic { get; } = new AzureSearchQueryType(SemanticValue); + /// Represents vector search over computed data. + public static AzureSearchQueryType Vector { get; } = new AzureSearchQueryType(VectorValue); + /// Represents a combination of the simple query strategy with vector data. + public static AzureSearchQueryType VectorSimpleHybrid { get; } = new AzureSearchQueryType(VectorSimpleHybridValue); + /// Represents a combination of semantic search and vector data querying. + public static AzureSearchQueryType VectorSemanticHybrid { get; } = new AzureSearchQueryType(VectorSemanticHybridValue); + /// Determines if two values are the same. + public static bool operator ==(AzureSearchQueryType left, AzureSearchQueryType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AzureSearchQueryType left, AzureSearchQueryType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AzureSearchQueryType(string value) => new AzureSearchQueryType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AzureSearchQueryType other && Equals(other); + /// + public bool Equals(AzureSearchQueryType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.Serialization.cs new file mode 100644 index 000000000000..79d6829b5c41 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.Serialization.cs @@ -0,0 +1,422 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class Batch : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OpenAI.Batch)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (Optional.IsDefined(Endpoint)) + { + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(Endpoint); + } + if (Optional.IsDefined(Errors)) + { + writer.WritePropertyName("errors"u8); + writer.WriteObjectValue(Errors, options); + } + writer.WritePropertyName("input_file_id"u8); + writer.WriteStringValue(InputFileId); + if (Optional.IsDefined(CompletionWindow)) + { + writer.WritePropertyName("completion_window"u8); + writer.WriteStringValue(CompletionWindow); + } + if (Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.Value.ToString()); + } + if (Optional.IsDefined(OutputFileId)) + { + writer.WritePropertyName("output_file_id"u8); + writer.WriteStringValue(OutputFileId); + } + if (Optional.IsDefined(ErrorFileId)) + { + writer.WritePropertyName("error_file_id"u8); + writer.WriteStringValue(ErrorFileId); + } + if (Optional.IsDefined(CreatedAt)) + { + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt.Value, "U"); + } + if (Optional.IsDefined(InProgressAt)) + { + writer.WritePropertyName("in_progress_at"u8); + writer.WriteNumberValue(InProgressAt.Value, "U"); + } + if (Optional.IsDefined(ExpiresAt)) + { + writer.WritePropertyName("expires_at"u8); + writer.WriteNumberValue(ExpiresAt.Value, "U"); + } + if (Optional.IsDefined(FinalizingAt)) + { + writer.WritePropertyName("finalizing_at"u8); + writer.WriteNumberValue(FinalizingAt.Value, "U"); + } + if (Optional.IsDefined(CompletedAt)) + { + writer.WritePropertyName("completed_at"u8); + writer.WriteNumberValue(CompletedAt.Value, "U"); + } + if (Optional.IsDefined(FailedAt)) + { + writer.WritePropertyName("failed_at"u8); + writer.WriteNumberValue(FailedAt.Value, "U"); + } + if (Optional.IsDefined(ExpiredAt)) + { + writer.WritePropertyName("expired_at"u8); + writer.WriteNumberValue(ExpiredAt.Value, "U"); + } + if (Optional.IsDefined(CancellingAt)) + { + writer.WritePropertyName("cancelling_at"u8); + writer.WriteNumberValue(CancellingAt.Value, "U"); + } + if (Optional.IsDefined(CancelledAt)) + { + writer.WritePropertyName("cancelled_at"u8); + writer.WriteNumberValue(CancelledAt.Value, "U"); + } + if (Optional.IsDefined(RequestCounts)) + { + writer.WritePropertyName("request_counts"u8); + writer.WriteObjectValue(RequestCounts, options); + } + if (Optional.IsCollectionDefined(Metadata)) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OpenAI.Batch 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(OpenAI.Batch)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return OpenAI.Batch.DeserializeBatch(document.RootElement, options); + } + + internal static OpenAI.Batch DeserializeBatch(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + BatchObject @object = default; + string endpoint = default; + BatchErrorList errors = default; + string inputFileId = default; + string completionWindow = default; + BatchStatus? status = default; + string outputFileId = default; + string errorFileId = default; + DateTimeOffset? createdAt = default; + DateTimeOffset? inProgressAt = default; + DateTimeOffset? expiresAt = default; + DateTimeOffset? finalizingAt = default; + DateTimeOffset? completedAt = default; + DateTimeOffset? failedAt = default; + DateTimeOffset? expiredAt = default; + DateTimeOffset? cancellingAt = default; + DateTimeOffset? cancelledAt = default; + BatchRequestCounts requestCounts = default; + IReadOnlyDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new BatchObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("endpoint"u8)) + { + endpoint = property.Value.GetString(); + continue; + } + if (property.NameEquals("errors"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + errors = BatchErrorList.DeserializeBatchErrorList(property.Value, options); + continue; + } + if (property.NameEquals("input_file_id"u8)) + { + inputFileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("completion_window"u8)) + { + completionWindow = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new BatchStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("output_file_id"u8)) + { + outputFileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("error_file_id"u8)) + { + errorFileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("in_progress_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + inProgressAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("expires_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("finalizing_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + finalizingAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("completed_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + completedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("failed_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + failedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("expired_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expiredAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("cancelling_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + cancellingAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("cancelled_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + cancelledAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("request_counts"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + requestCounts = BatchRequestCounts.DeserializeBatchRequestCounts(property.Value, options); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OpenAI.Batch( + id, + @object, + endpoint, + errors, + inputFileId, + completionWindow, + status, + outputFileId, + errorFileId, + createdAt, + inProgressAt, + expiresAt, + finalizingAt, + completedAt, + failedAt, + expiredAt, + cancellingAt, + cancelledAt, + requestCounts, + metadata ?? new ChangeTrackingDictionary(), + serializedAdditionalRawData); + } + + 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(OpenAI.Batch)} does not support writing '{options.Format}' format."); + } + } + + OpenAI.Batch 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 OpenAI.Batch.DeserializeBatch(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OpenAI.Batch)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OpenAI.Batch FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return OpenAI.Batch.DeserializeBatch(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.cs new file mode 100644 index 000000000000..6bed6d1a92f9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The Batch object. + internal partial class Batch + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The id assigned to the Batch. + /// The ID of the input file for the batch. + /// or is null. + internal Batch(string id, string inputFileId) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(inputFileId, nameof(inputFileId)); + + Id = id; + InputFileId = inputFileId; + Metadata = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// The id assigned to the Batch. + /// The object type, which is always `batch`. + /// The OpenAI API endpoint used by the batch. + /// The list of Batch errors. + /// The ID of the input file for the batch. + /// The time frame within which the batch should be processed. + /// The current status of the batch. + /// The ID of the file containing the outputs of successfully executed requests. + /// The ID of the file containing the outputs of requests with errors. + /// The Unix timestamp (in seconds) for when the batch was created. + /// The Unix timestamp (in seconds) for when the batch started processing. + /// The Unix timestamp (in seconds) for when the batch will expire. + /// The Unix timestamp (in seconds) for when the batch started finalizing. + /// The Unix timestamp (in seconds) for when the batch was completed. + /// The Unix timestamp (in seconds) for when the batch failed. + /// The Unix timestamp (in seconds) for when the batch expired. + /// The Unix timestamp (in seconds) for when the batch started cancelling. + /// The Unix timestamp (in seconds) for when the batch was cancelled. + /// The request counts for different statuses within the batch. + /// A set of key-value pairs that can be attached to the batch. This can be useful for storing additional information about the batch in a structured format. + /// Keeps track of any properties unknown to the library. + internal Batch(string id, BatchObject @object, string endpoint, BatchErrorList errors, string inputFileId, string completionWindow, BatchStatus? status, string outputFileId, string errorFileId, DateTimeOffset? createdAt, DateTimeOffset? inProgressAt, DateTimeOffset? expiresAt, DateTimeOffset? finalizingAt, DateTimeOffset? completedAt, DateTimeOffset? failedAt, DateTimeOffset? expiredAt, DateTimeOffset? cancellingAt, DateTimeOffset? cancelledAt, BatchRequestCounts requestCounts, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + { + Id = id; + Object = @object; + Endpoint = endpoint; + Errors = errors; + InputFileId = inputFileId; + CompletionWindow = completionWindow; + Status = status; + OutputFileId = outputFileId; + ErrorFileId = errorFileId; + CreatedAt = createdAt; + InProgressAt = inProgressAt; + ExpiresAt = expiresAt; + FinalizingAt = finalizingAt; + CompletedAt = completedAt; + FailedAt = failedAt; + ExpiredAt = expiredAt; + CancellingAt = cancellingAt; + CancelledAt = cancelledAt; + RequestCounts = requestCounts; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Batch() + { + } + + /// The id assigned to the Batch. + public string Id { get; } + /// The object type, which is always `batch`. + public BatchObject Object { get; } = BatchObject.Batch; + + /// The OpenAI API endpoint used by the batch. + public string Endpoint { get; } + /// The list of Batch errors. + public BatchErrorList Errors { get; } + /// The ID of the input file for the batch. + public string InputFileId { get; } + /// The time frame within which the batch should be processed. + public string CompletionWindow { get; } + /// The current status of the batch. + public BatchStatus? Status { get; } + /// The ID of the file containing the outputs of successfully executed requests. + public string OutputFileId { get; } + /// The ID of the file containing the outputs of requests with errors. + public string ErrorFileId { get; } + /// The Unix timestamp (in seconds) for when the batch was created. + public DateTimeOffset? CreatedAt { get; } + /// The Unix timestamp (in seconds) for when the batch started processing. + public DateTimeOffset? InProgressAt { get; } + /// The Unix timestamp (in seconds) for when the batch will expire. + public DateTimeOffset? ExpiresAt { get; } + /// The Unix timestamp (in seconds) for when the batch started finalizing. + public DateTimeOffset? FinalizingAt { get; } + /// The Unix timestamp (in seconds) for when the batch was completed. + public DateTimeOffset? CompletedAt { get; } + /// The Unix timestamp (in seconds) for when the batch failed. + public DateTimeOffset? FailedAt { get; } + /// The Unix timestamp (in seconds) for when the batch expired. + public DateTimeOffset? ExpiredAt { get; } + /// The Unix timestamp (in seconds) for when the batch started cancelling. + public DateTimeOffset? CancellingAt { get; } + /// The Unix timestamp (in seconds) for when the batch was cancelled. + public DateTimeOffset? CancelledAt { get; } + /// The request counts for different statuses within the batch. + public BatchRequestCounts RequestCounts { get; } + /// A set of key-value pairs that can be attached to the batch. This can be useful for storing additional information about the batch in a structured format. + public IReadOnlyDictionary Metadata { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.Serialization.cs new file mode 100644 index 000000000000..0c22a90dc257 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.Serialization.cs @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class BatchCreateRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(BatchCreateRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(Endpoint); + writer.WritePropertyName("input_file_id"u8); + writer.WriteStringValue(InputFileId); + writer.WritePropertyName("completion_window"u8); + writer.WriteStringValue(CompletionWindow); + if (Optional.IsCollectionDefined(Metadata)) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + BatchCreateRequest 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(BatchCreateRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchCreateRequest(document.RootElement, options); + } + + internal static BatchCreateRequest DeserializeBatchCreateRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string endpoint = default; + string inputFileId = default; + string completionWindow = default; + IDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("endpoint"u8)) + { + endpoint = property.Value.GetString(); + continue; + } + if (property.NameEquals("input_file_id"u8)) + { + inputFileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("completion_window"u8)) + { + completionWindow = property.Value.GetString(); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchCreateRequest(endpoint, inputFileId, completionWindow, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + } + + 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(BatchCreateRequest)} does not support writing '{options.Format}' format."); + } + } + + BatchCreateRequest 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 DeserializeBatchCreateRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchCreateRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchCreateRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeBatchCreateRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.cs new file mode 100644 index 000000000000..b041ee731672 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Defines the request to create a batch. + public partial class BatchCreateRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The API endpoint used by the batch. + /// The ID of the input file for the batch. + /// The time frame within which the batch should be processed. + /// , or is null. + public BatchCreateRequest(string endpoint, string inputFileId, string completionWindow) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(inputFileId, nameof(inputFileId)); + Argument.AssertNotNull(completionWindow, nameof(completionWindow)); + + Endpoint = endpoint; + InputFileId = inputFileId; + CompletionWindow = completionWindow; + Metadata = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// The API endpoint used by the batch. + /// The ID of the input file for the batch. + /// The time frame within which the batch should be processed. + /// A set of key-value pairs that can be attached to the batch. This can be useful for storing additional information about the batch in a structured format. + /// Keeps track of any properties unknown to the library. + internal BatchCreateRequest(string endpoint, string inputFileId, string completionWindow, IDictionary metadata, IDictionary serializedAdditionalRawData) + { + Endpoint = endpoint; + InputFileId = inputFileId; + CompletionWindow = completionWindow; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal BatchCreateRequest() + { + } + + /// The API endpoint used by the batch. + public string Endpoint { get; } + /// The ID of the input file for the batch. + public string InputFileId { get; } + /// The time frame within which the batch should be processed. + public string CompletionWindow { get; } + /// A set of key-value pairs that can be attached to the batch. This can be useful for storing additional information about the batch in a structured format. + public IDictionary Metadata { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.Serialization.cs new file mode 100644 index 000000000000..2927203aeba0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.Serialization.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class BatchErrorDatum : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(BatchErrorDatum)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Code)) + { + writer.WritePropertyName("code"u8); + writer.WriteStringValue(Code); + } + if (Optional.IsDefined(Message)) + { + writer.WritePropertyName("message"u8); + writer.WriteStringValue(Message); + } + if (Optional.IsDefined(Param)) + { + writer.WritePropertyName("param"u8); + writer.WriteStringValue(Param); + } + if (Optional.IsDefined(Line)) + { + writer.WritePropertyName("line"u8); + writer.WriteNumberValue(Line.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + BatchErrorDatum 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(BatchErrorDatum)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchErrorDatum(document.RootElement, options); + } + + internal static BatchErrorDatum DeserializeBatchErrorDatum(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string code = default; + string message = default; + string param = default; + int? line = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code"u8)) + { + code = property.Value.GetString(); + continue; + } + if (property.NameEquals("message"u8)) + { + message = property.Value.GetString(); + continue; + } + if (property.NameEquals("param"u8)) + { + param = property.Value.GetString(); + continue; + } + if (property.NameEquals("line"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + line = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchErrorDatum(code, message, param, line, serializedAdditionalRawData); + } + + 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(BatchErrorDatum)} does not support writing '{options.Format}' format."); + } + } + + BatchErrorDatum 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 DeserializeBatchErrorDatum(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchErrorDatum)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchErrorDatum FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeBatchErrorDatum(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.cs new file mode 100644 index 000000000000..456d267b86e9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A Datum containing information about a Batch Error. + internal partial class BatchErrorDatum + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal BatchErrorDatum() + { + } + + /// Initializes a new instance of . + /// An error code identifying the error type. + /// A human-readable message providing more details about the error. + /// The name of the parameter that caused the error, if applicable. + /// The line number of the input file where the error occurred, if applicable. + /// Keeps track of any properties unknown to the library. + internal BatchErrorDatum(string code, string message, string param, int? line, IDictionary serializedAdditionalRawData) + { + Code = code; + Message = message; + Param = param; + Line = line; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// An error code identifying the error type. + public string Code { get; } + /// A human-readable message providing more details about the error. + public string Message { get; } + /// The name of the parameter that caused the error, if applicable. + public string Param { get; } + /// The line number of the input file where the error occurred, if applicable. + public int? Line { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.Serialization.cs new file mode 100644 index 000000000000..284fb6d99917 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class BatchErrorList : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(BatchErrorList)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (Optional.IsCollectionDefined(Data)) + { + writer.WritePropertyName("data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + BatchErrorList 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(BatchErrorList)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchErrorList(document.RootElement, options); + } + + internal static BatchErrorList DeserializeBatchErrorList(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BatchErrorListObject @object = default; + IReadOnlyList data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("object"u8)) + { + @object = new BatchErrorListObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("data"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(BatchErrorDatum.DeserializeBatchErrorDatum(item, options)); + } + data = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchErrorList(@object, data ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + 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(BatchErrorList)} does not support writing '{options.Format}' format."); + } + } + + BatchErrorList 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 DeserializeBatchErrorList(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchErrorList)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchErrorList FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeBatchErrorList(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.cs new file mode 100644 index 000000000000..29f92fdc83cf --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A list of Batch errors. + internal partial class BatchErrorList + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal BatchErrorList() + { + Data = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The object type, which is always `list`. + /// The list of Batch error data. + /// Keeps track of any properties unknown to the library. + internal BatchErrorList(BatchErrorListObject @object, IReadOnlyList data, IDictionary serializedAdditionalRawData) + { + Object = @object; + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type, which is always `list`. + public BatchErrorListObject Object { get; } = BatchErrorListObject.List; + + /// The list of Batch error data. + public IReadOnlyList Data { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorListObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorListObject.cs new file mode 100644 index 000000000000..55ccfecd62da --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorListObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The BatchErrorList_object. + internal readonly partial struct BatchErrorListObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public BatchErrorListObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ListValue = "list"; + + /// list. + public static BatchErrorListObject List { get; } = new BatchErrorListObject(ListValue); + /// Determines if two values are the same. + public static bool operator ==(BatchErrorListObject left, BatchErrorListObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(BatchErrorListObject left, BatchErrorListObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator BatchErrorListObject(string value) => new BatchErrorListObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is BatchErrorListObject other && Equals(other); + /// + public bool Equals(BatchErrorListObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchObject.cs new file mode 100644 index 000000000000..7d9b06bdf500 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The Batch_object. + internal readonly partial struct BatchObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public BatchObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string BatchValue = "batch"; + + /// batch. + public static BatchObject Batch { get; } = new BatchObject(BatchValue); + /// Determines if two values are the same. + public static bool operator ==(BatchObject left, BatchObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(BatchObject left, BatchObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator BatchObject(string value) => new BatchObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is BatchObject other && Equals(other); + /// + public bool Equals(BatchObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.Serialization.cs new file mode 100644 index 000000000000..1c6ab637fa8f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.Serialization.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class BatchRequestCounts : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(BatchRequestCounts)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Total)) + { + writer.WritePropertyName("total"u8); + writer.WriteNumberValue(Total.Value); + } + if (Optional.IsDefined(Completed)) + { + writer.WritePropertyName("completed"u8); + writer.WriteNumberValue(Completed.Value); + } + if (Optional.IsDefined(Failed)) + { + writer.WritePropertyName("failed"u8); + writer.WriteNumberValue(Failed.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + BatchRequestCounts 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(BatchRequestCounts)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchRequestCounts(document.RootElement, options); + } + + internal static BatchRequestCounts DeserializeBatchRequestCounts(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? total = default; + int? completed = default; + int? failed = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("total"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + total = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("completed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + completed = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("failed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + failed = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchRequestCounts(total, completed, failed, serializedAdditionalRawData); + } + + 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(BatchRequestCounts)} does not support writing '{options.Format}' format."); + } + } + + BatchRequestCounts 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 DeserializeBatchRequestCounts(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchRequestCounts)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchRequestCounts FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeBatchRequestCounts(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.cs new file mode 100644 index 000000000000..014a428c108f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The BatchRequestCounts. + internal partial class BatchRequestCounts + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal BatchRequestCounts() + { + } + + /// Initializes a new instance of . + /// Total number of requests in the batch. + /// Number of requests that have been completed successfully. + /// Number of requests that have failed. + /// Keeps track of any properties unknown to the library. + internal BatchRequestCounts(int? total, int? completed, int? failed, IDictionary serializedAdditionalRawData) + { + Total = total; + Completed = completed; + Failed = failed; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Total number of requests in the batch. + public int? Total { get; } + /// Number of requests that have been completed successfully. + public int? Completed { get; } + /// Number of requests that have failed. + public int? Failed { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchStatus.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchStatus.cs new file mode 100644 index 000000000000..421a0f16f186 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchStatus.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The status of a batch. + internal readonly partial struct BatchStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public BatchStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ValidatingValue = "validating"; + private const string FailedValue = "failed"; + private const string InProgressValue = "in_progress"; + private const string FinalizingValue = "finalizing"; + private const string CompletedValue = "completed"; + private const string ExpiredValue = "expired"; + private const string CancellingValue = "cancelling"; + private const string CancelledValue = "cancelled"; + + /// The input file is being validated before the batch can begin. + public static BatchStatus Validating { get; } = new BatchStatus(ValidatingValue); + /// The input file has failed the validation process. + public static BatchStatus Failed { get; } = new BatchStatus(FailedValue); + /// The input file was successfully validated and the batch is currently being executed. + public static BatchStatus InProgress { get; } = new BatchStatus(InProgressValue); + /// The batch has completed and the results are being prepared. + public static BatchStatus Finalizing { get; } = new BatchStatus(FinalizingValue); + /// The batch has been completed and the results are ready. + public static BatchStatus Completed { get; } = new BatchStatus(CompletedValue); + /// The batch was not able to complete within the 24-hour time window. + public static BatchStatus Expired { get; } = new BatchStatus(ExpiredValue); + /// Cancellation of the batch has been initiated. + public static BatchStatus Cancelling { get; } = new BatchStatus(CancellingValue); + /// The batch was cancelled. + public static BatchStatus Cancelled { get; } = new BatchStatus(CancelledValue); + /// Determines if two values are the same. + public static bool operator ==(BatchStatus left, BatchStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(BatchStatus left, BatchStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator BatchStatus(string value) => new BatchStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is BatchStatus other && Equals(other); + /// + public bool Equals(BatchStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.Serialization.cs new file mode 100644 index 000000000000..6deefb3ba214 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.Serialization.cs @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatChoice : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatChoice)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Message)) + { + writer.WritePropertyName("message"u8); + writer.WriteObjectValue(Message, options); + } + if (LogProbabilityInfo != null) + { + writer.WritePropertyName("logprobs"u8); + writer.WriteObjectValue(LogProbabilityInfo, options); + } + else + { + writer.WriteNull("logprobs"); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + if (FinishReason != null) + { + writer.WritePropertyName("finish_reason"u8); + writer.WriteStringValue(FinishReason.Value.ToString()); + } + else + { + writer.WriteNull("finish_reason"); + } + if (Optional.IsDefined(InternalStreamingDeltaMessage)) + { + writer.WritePropertyName("delta"u8); + writer.WriteObjectValue(InternalStreamingDeltaMessage, options); + } + if (Optional.IsDefined(ContentFilterResults)) + { + writer.WritePropertyName("content_filter_results"u8); + writer.WriteObjectValue(ContentFilterResults, options); + } + if (Optional.IsDefined(Enhancements)) + { + writer.WritePropertyName("enhancements"u8); + writer.WriteObjectValue(Enhancements, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatChoice 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(ChatChoice)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatChoice(document.RootElement, options); + } + + internal static ChatChoice DeserializeChatChoice(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatResponseMessage message = default; + ChatChoiceLogProbabilityInfo logprobs = default; + int index = default; + CompletionsFinishReason? finishReason = default; + ChatResponseMessage delta = default; + ContentFilterResultsForChoice contentFilterResults = default; + AzureChatEnhancements enhancements = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("message"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + message = ChatResponseMessage.DeserializeChatResponseMessage(property.Value, options); + continue; + } + if (property.NameEquals("logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + logprobs = null; + continue; + } + logprobs = ChatChoiceLogProbabilityInfo.DeserializeChatChoiceLogProbabilityInfo(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("finish_reason"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + finishReason = null; + continue; + } + finishReason = new CompletionsFinishReason(property.Value.GetString()); + continue; + } + if (property.NameEquals("delta"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + delta = ChatResponseMessage.DeserializeChatResponseMessage(property.Value, options); + continue; + } + if (property.NameEquals("content_filter_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + contentFilterResults = ContentFilterResultsForChoice.DeserializeContentFilterResultsForChoice(property.Value, options); + continue; + } + if (property.NameEquals("enhancements"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + enhancements = AzureChatEnhancements.DeserializeAzureChatEnhancements(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatChoice( + message, + logprobs, + index, + finishReason, + delta, + contentFilterResults, + enhancements, + serializedAdditionalRawData); + } + + 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(ChatChoice)} does not support writing '{options.Format}' format."); + } + } + + ChatChoice 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 DeserializeChatChoice(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatChoice)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatChoice FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatChoice(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.cs new file mode 100644 index 000000000000..4e85fb934a30 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// The representation of a single prompt completion as part of an overall chat completions request. + /// Generally, `n` choices are generated per provided prompt with a default value of 1. + /// Token limits and other settings may limit the number of choices generated. + /// + public partial class ChatChoice + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The log probability information for this choice, as enabled via the 'logprobs' request option. + /// The ordered index associated with this chat completions choice. + /// The reason that this chat completions choice completed its generated. + internal ChatChoice(ChatChoiceLogProbabilityInfo logProbabilityInfo, int index, CompletionsFinishReason? finishReason) + { + LogProbabilityInfo = logProbabilityInfo; + Index = index; + FinishReason = finishReason; + } + + /// Initializes a new instance of . + /// The chat message for a given chat completions prompt. + /// The log probability information for this choice, as enabled via the 'logprobs' request option. + /// The ordered index associated with this chat completions choice. + /// The reason that this chat completions choice completed its generated. + /// The delta message content for a streaming response. + /// + /// Information about the content filtering category (hate, sexual, violence, self_harm), if it + /// has been detected, as well as the severity level (very_low, low, medium, high-scale that + /// determines the intensity and risk level of harmful content) and if it has been filtered or not. + /// + /// + /// Represents the output results of Azure OpenAI enhancements to chat completions, as configured via the matching input + /// provided in the request. This supplementary information is only available when using Azure OpenAI and only when the + /// request is configured to use enhancements. + /// + /// Keeps track of any properties unknown to the library. + internal ChatChoice(ChatResponseMessage message, ChatChoiceLogProbabilityInfo logProbabilityInfo, int index, CompletionsFinishReason? finishReason, ChatResponseMessage internalStreamingDeltaMessage, ContentFilterResultsForChoice contentFilterResults, AzureChatEnhancements enhancements, IDictionary serializedAdditionalRawData) + { + Message = message; + LogProbabilityInfo = logProbabilityInfo; + Index = index; + FinishReason = finishReason; + InternalStreamingDeltaMessage = internalStreamingDeltaMessage; + ContentFilterResults = contentFilterResults; + Enhancements = enhancements; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatChoice() + { + } + + /// The chat message for a given chat completions prompt. + public ChatResponseMessage Message { get; } + /// The log probability information for this choice, as enabled via the 'logprobs' request option. + public ChatChoiceLogProbabilityInfo LogProbabilityInfo { get; } + /// The ordered index associated with this chat completions choice. + public int Index { get; } + /// The reason that this chat completions choice completed its generated. + public CompletionsFinishReason? FinishReason { get; } + /// The delta message content for a streaming response. + public ChatResponseMessage InternalStreamingDeltaMessage { get; } + /// + /// Information about the content filtering category (hate, sexual, violence, self_harm), if it + /// has been detected, as well as the severity level (very_low, low, medium, high-scale that + /// determines the intensity and risk level of harmful content) and if it has been filtered or not. + /// + public ContentFilterResultsForChoice ContentFilterResults { get; } + /// + /// Represents the output results of Azure OpenAI enhancements to chat completions, as configured via the matching input + /// provided in the request. This supplementary information is only available when using Azure OpenAI and only when the + /// request is configured to use enhancements. + /// + public AzureChatEnhancements Enhancements { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.Serialization.cs new file mode 100644 index 000000000000..279e4fa7bd7c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.Serialization.cs @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatChoiceLogProbabilityInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatChoiceLogProbabilityInfo)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (TokenLogProbabilityResults != null && Optional.IsCollectionDefined(TokenLogProbabilityResults)) + { + writer.WritePropertyName("content"u8); + writer.WriteStartArray(); + foreach (var item in TokenLogProbabilityResults) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("content"); + } + if (Refusal != null && Optional.IsCollectionDefined(Refusal)) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStartArray(); + foreach (var item in Refusal) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("refusal"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatChoiceLogProbabilityInfo 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(ChatChoiceLogProbabilityInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatChoiceLogProbabilityInfo(document.RootElement, options); + } + + internal static ChatChoiceLogProbabilityInfo DeserializeChatChoiceLogProbabilityInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList content = default; + IReadOnlyList refusal = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + content = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatTokenLogProbabilityResult.DeserializeChatTokenLogProbabilityResult(item, options)); + } + content = array; + continue; + } + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + refusal = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatTokenLogProbabilityResult.DeserializeChatTokenLogProbabilityResult(item, options)); + } + refusal = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatChoiceLogProbabilityInfo(content, refusal, serializedAdditionalRawData); + } + + 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(ChatChoiceLogProbabilityInfo)} does not support writing '{options.Format}' format."); + } + } + + ChatChoiceLogProbabilityInfo 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 DeserializeChatChoiceLogProbabilityInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatChoiceLogProbabilityInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatChoiceLogProbabilityInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatChoiceLogProbabilityInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.cs new file mode 100644 index 000000000000..f2343104bd0a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Log probability information for a choice, as requested via 'logprobs' and 'top_logprobs'. + public partial class ChatChoiceLogProbabilityInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. + /// The list of log probability information entries for the choice's message refusal message tokens, as requested via the 'logprobs' option. + internal ChatChoiceLogProbabilityInfo(IEnumerable tokenLogProbabilityResults, IEnumerable refusal) + { + TokenLogProbabilityResults = tokenLogProbabilityResults?.ToList(); + Refusal = refusal?.ToList(); + } + + /// Initializes a new instance of . + /// The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. + /// The list of log probability information entries for the choice's message refusal message tokens, as requested via the 'logprobs' option. + /// Keeps track of any properties unknown to the library. + internal ChatChoiceLogProbabilityInfo(IReadOnlyList tokenLogProbabilityResults, IReadOnlyList refusal, IDictionary serializedAdditionalRawData) + { + TokenLogProbabilityResults = tokenLogProbabilityResults; + Refusal = refusal; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatChoiceLogProbabilityInfo() + { + } + + /// The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. + public IReadOnlyList TokenLogProbabilityResults { get; } + /// The list of log probability information entries for the choice's message refusal message tokens, as requested via the 'logprobs' option. + public IReadOnlyList Refusal { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.Serialization.cs new file mode 100644 index 000000000000..568fdd061570 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionStreamOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionStreamOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(IncludeUsage)) + { + writer.WritePropertyName("include_usage"u8); + writer.WriteBooleanValue(IncludeUsage.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionStreamOptions 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(ChatCompletionStreamOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionStreamOptions(document.RootElement, options); + } + + internal static ChatCompletionStreamOptions DeserializeChatCompletionStreamOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool? includeUsage = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("include_usage"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + includeUsage = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionStreamOptions(includeUsage, serializedAdditionalRawData); + } + + 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(ChatCompletionStreamOptions)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionStreamOptions 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 DeserializeChatCompletionStreamOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionStreamOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionStreamOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionStreamOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.cs new file mode 100644 index 000000000000..2dba2eb70309 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Options for streaming response. Only set this when you set `stream: true`. + public partial class ChatCompletionStreamOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public ChatCompletionStreamOptions() + { + } + + /// Initializes a new instance of . + /// If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionStreamOptions(bool? includeUsage, IDictionary serializedAdditionalRawData) + { + IncludeUsage = includeUsage; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value. + public bool? IncludeUsage { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.Serialization.cs new file mode 100644 index 000000000000..925fb3ca69c6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.Serialization.cs @@ -0,0 +1,224 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("created"u8); + writer.WriteNumberValue(Created, "U"); + writer.WritePropertyName("choices"u8); + writer.WriteStartArray(); + foreach (var item in Choices) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (Optional.IsDefined(Model)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model); + } + if (Optional.IsCollectionDefined(PromptFilterResults)) + { + writer.WritePropertyName("prompt_filter_results"u8); + writer.WriteStartArray(); + foreach (var item in PromptFilterResults) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(SystemFingerprint)) + { + writer.WritePropertyName("system_fingerprint"u8); + writer.WriteStringValue(SystemFingerprint); + } + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletions 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(ChatCompletions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletions(document.RootElement, options); + } + + internal static ChatCompletions DeserializeChatCompletions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset created = default; + IReadOnlyList choices = default; + string model = default; + IReadOnlyList promptFilterResults = default; + string systemFingerprint = default; + CompletionsUsage usage = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("created"u8)) + { + created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("choices"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatChoice.DeserializeChatChoice(item, options)); + } + choices = array; + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (property.NameEquals("prompt_filter_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ContentFilterResultsForPrompt.DeserializeContentFilterResultsForPrompt(item, options)); + } + promptFilterResults = array; + continue; + } + if (property.NameEquals("system_fingerprint"u8)) + { + systemFingerprint = property.Value.GetString(); + continue; + } + if (property.NameEquals("usage"u8)) + { + usage = CompletionsUsage.DeserializeCompletionsUsage(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletions( + id, + created, + choices, + model, + promptFilterResults ?? new ChangeTrackingList(), + systemFingerprint, + usage, + serializedAdditionalRawData); + } + + 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(ChatCompletions)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletions 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 DeserializeChatCompletions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.cs new file mode 100644 index 000000000000..e50eb5c47d75 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// Representation of the response data from a chat completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + public partial class ChatCompletions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A unique identifier associated with this chat completions response. + /// + /// The first timestamp associated with generation activity for this completions response, + /// represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. + /// + /// + /// The collection of completions choices associated with this completions response. + /// Generally, `n` choices are generated per provided prompt with a default value of 1. + /// Token limits and other settings may limit the number of choices generated. + /// + /// Usage information for tokens processed and generated as part of this completions operation. + /// , or is null. + internal ChatCompletions(string id, DateTimeOffset created, IEnumerable choices, CompletionsUsage usage) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(choices, nameof(choices)); + Argument.AssertNotNull(usage, nameof(usage)); + + Id = id; + Created = created; + Choices = choices.ToList(); + PromptFilterResults = new ChangeTrackingList(); + Usage = usage; + } + + /// Initializes a new instance of . + /// A unique identifier associated with this chat completions response. + /// + /// The first timestamp associated with generation activity for this completions response, + /// represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. + /// + /// + /// The collection of completions choices associated with this completions response. + /// Generally, `n` choices are generated per provided prompt with a default value of 1. + /// Token limits and other settings may limit the number of choices generated. + /// + /// The model name used for this completions request. + /// + /// Content filtering results for zero or more prompts in the request. In a streaming request, + /// results for different prompts may arrive at different times or in different orders. + /// + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that + /// might impact determinism. + /// + /// Usage information for tokens processed and generated as part of this completions operation. + /// Keeps track of any properties unknown to the library. + internal ChatCompletions(string id, DateTimeOffset created, IReadOnlyList choices, string model, IReadOnlyList promptFilterResults, string systemFingerprint, CompletionsUsage usage, IDictionary serializedAdditionalRawData) + { + Id = id; + Created = created; + Choices = choices; + Model = model; + PromptFilterResults = promptFilterResults; + SystemFingerprint = systemFingerprint; + Usage = usage; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletions() + { + } + + /// A unique identifier associated with this chat completions response. + public string Id { get; } + /// + /// The first timestamp associated with generation activity for this completions response, + /// represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. + /// + public DateTimeOffset Created { get; } + /// + /// The collection of completions choices associated with this completions response. + /// Generally, `n` choices are generated per provided prompt with a default value of 1. + /// Token limits and other settings may limit the number of choices generated. + /// + public IReadOnlyList Choices { get; } + /// The model name used for this completions request. + public string Model { get; } + /// + /// Content filtering results for zero or more prompts in the request. In a streaming request, + /// results for different prompts may arrive at different times or in different orders. + /// + public IReadOnlyList PromptFilterResults { get; } + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that + /// might impact determinism. + /// + public string SystemFingerprint { get; } + /// Usage information for tokens processed and generated as part of this completions operation. + public CompletionsUsage Usage { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.Serialization.cs new file mode 100644 index 000000000000..b7ee9e7b8f91 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsFunctionToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsFunctionToolCall)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsFunctionToolCall 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(ChatCompletionsFunctionToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsFunctionToolCall(document.RootElement, options); + } + + internal static ChatCompletionsFunctionToolCall DeserializeChatCompletionsFunctionToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + FunctionCall function = default; + string type = default; + string id = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("function"u8)) + { + function = FunctionCall.DeserializeFunctionCall(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsFunctionToolCall(type, id, serializedAdditionalRawData, function); + } + + 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(ChatCompletionsFunctionToolCall)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsFunctionToolCall 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 DeserializeChatCompletionsFunctionToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsFunctionToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsFunctionToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.cs new file mode 100644 index 000000000000..97a6d2211fd9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A tool call to a function tool, issued by the model in evaluation of a configured function tool, that represents + /// a function invocation needed for a subsequent chat completions request to resolve. + /// + public partial class ChatCompletionsFunctionToolCall : ChatCompletionsToolCall + { + /// Initializes a new instance of . + /// The ID of the tool call. + /// The details of the function invocation requested by the tool call. + /// or is null. + public ChatCompletionsFunctionToolCall(string id, FunctionCall function) : base(id) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(function, nameof(function)); + + Type = "function"; + Function = function; + } + + /// Initializes a new instance of . + /// The object type. + /// The ID of the tool call. + /// Keeps track of any properties unknown to the library. + /// The details of the function invocation requested by the tool call. + internal ChatCompletionsFunctionToolCall(string type, string id, IDictionary serializedAdditionalRawData, FunctionCall function) : base(type, id, serializedAdditionalRawData) + { + Function = function; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsFunctionToolCall() + { + } + + /// The details of the function invocation requested by the tool call. + public FunctionCall Function { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.Serialization.cs new file mode 100644 index 000000000000..49de20793814 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsFunctionToolDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsFunctionToolDefinition)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsFunctionToolDefinition 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(ChatCompletionsFunctionToolDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsFunctionToolDefinition(document.RootElement, options); + } + + internal static ChatCompletionsFunctionToolDefinition DeserializeChatCompletionsFunctionToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatCompletionsFunctionToolDefinitionFunction function = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("function"u8)) + { + function = ChatCompletionsFunctionToolDefinitionFunction.DeserializeChatCompletionsFunctionToolDefinitionFunction(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsFunctionToolDefinition(type, serializedAdditionalRawData, function); + } + + 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(ChatCompletionsFunctionToolDefinition)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsFunctionToolDefinition 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 DeserializeChatCompletionsFunctionToolDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsFunctionToolDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsFunctionToolDefinition(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.cs new file mode 100644 index 000000000000..7b1881366a9b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The definition information for a chat completions function tool that can call a function in response to a tool call. + public partial class ChatCompletionsFunctionToolDefinition : ChatCompletionsToolDefinition + { + /// Initializes a new instance of . + /// The function definition details for the function tool. + /// is null. + public ChatCompletionsFunctionToolDefinition(ChatCompletionsFunctionToolDefinitionFunction function) + { + Argument.AssertNotNull(function, nameof(function)); + + Type = "function"; + Function = function; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + /// The function definition details for the function tool. + internal ChatCompletionsFunctionToolDefinition(string type, IDictionary serializedAdditionalRawData, ChatCompletionsFunctionToolDefinitionFunction function) : base(type, serializedAdditionalRawData) + { + Function = function; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsFunctionToolDefinition() + { + } + + /// The function definition details for the function tool. + public ChatCompletionsFunctionToolDefinitionFunction Function { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.Serialization.cs new file mode 100644 index 000000000000..3875fa6c7c08 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.Serialization.cs @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsFunctionToolDefinitionFunction : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsFunctionToolDefinitionFunction)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (Optional.IsDefined(Parameters)) + { + writer.WritePropertyName("parameters"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Parameters); +#else + using (JsonDocument document = JsonDocument.Parse(Parameters)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsDefined(Strict)) + { + if (Strict != null) + { + writer.WritePropertyName("strict"u8); + writer.WriteBooleanValue(Strict.Value); + } + else + { + writer.WriteNull("strict"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsFunctionToolDefinitionFunction 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(ChatCompletionsFunctionToolDefinitionFunction)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsFunctionToolDefinitionFunction(document.RootElement, options); + } + + internal static ChatCompletionsFunctionToolDefinitionFunction DeserializeChatCompletionsFunctionToolDefinitionFunction(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string description = default; + string name = default; + BinaryData parameters = default; + bool? strict = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("parameters"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parameters = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("strict"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + strict = null; + continue; + } + strict = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsFunctionToolDefinitionFunction(description, name, parameters, strict, serializedAdditionalRawData); + } + + 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(ChatCompletionsFunctionToolDefinitionFunction)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsFunctionToolDefinitionFunction 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 DeserializeChatCompletionsFunctionToolDefinitionFunction(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolDefinitionFunction)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsFunctionToolDefinitionFunction FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsFunctionToolDefinitionFunction(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.cs new file mode 100644 index 000000000000..03c565925bbd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The ChatCompletionsFunctionToolDefinitionFunction. + public partial class ChatCompletionsFunctionToolDefinitionFunction + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// is null. + public ChatCompletionsFunctionToolDefinitionFunction(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + /// Initializes a new instance of . + /// A description of what the function does, used by the model to choose when and how to call the function. + /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// + /// Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling). + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsFunctionToolDefinitionFunction(string description, string name, BinaryData parameters, bool? strict, IDictionary serializedAdditionalRawData) + { + Description = description; + Name = name; + Parameters = parameters; + Strict = strict; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsFunctionToolDefinitionFunction() + { + } + + /// A description of what the function does, used by the model to choose when and how to call the function. + public string Description { get; set; } + /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + public string Name { get; } + /// + /// Gets or sets the parameters + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Parameters { get; set; } + /// Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling). + public bool? Strict { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.Serialization.cs new file mode 100644 index 000000000000..cde742459bf0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsFunctionToolSelection : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsFunctionToolSelection)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsFunctionToolSelection 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(ChatCompletionsFunctionToolSelection)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsFunctionToolSelection(document.RootElement, options); + } + + internal static ChatCompletionsFunctionToolSelection DeserializeChatCompletionsFunctionToolSelection(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsFunctionToolSelection(name, serializedAdditionalRawData); + } + + 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(ChatCompletionsFunctionToolSelection)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsFunctionToolSelection 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 DeserializeChatCompletionsFunctionToolSelection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolSelection)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsFunctionToolSelection FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsFunctionToolSelection(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.cs similarity index 65% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.cs index 5a1af0cc4664..419c61a67c34 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.cs @@ -8,10 +8,10 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI.Assistants +namespace Azure.AI.OpenAI { - /// The CreateAssistantFileRequest. - internal partial class CreateAssistantFileRequest + /// A tool selection of a specific, named function tool that will limit chat completions to using the named function. + public partial class ChatCompletionsFunctionToolSelection { /// /// Keeps track of any properties unknown to the library. @@ -45,31 +45,31 @@ internal partial class CreateAssistantFileRequest /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - /// The ID of the previously uploaded file to attach. - /// is null. - internal CreateAssistantFileRequest(string fileId) + /// Initializes a new instance of . + /// The name of the function that should be called. + /// is null. + public ChatCompletionsFunctionToolSelection(string name) { - Argument.AssertNotNull(fileId, nameof(fileId)); + Argument.AssertNotNull(name, nameof(name)); - FileId = fileId; + Name = name; } - /// Initializes a new instance of . - /// The ID of the previously uploaded file to attach. + /// Initializes a new instance of . + /// The name of the function that should be called. /// Keeps track of any properties unknown to the library. - internal CreateAssistantFileRequest(string fileId, IDictionary serializedAdditionalRawData) + internal ChatCompletionsFunctionToolSelection(string name, IDictionary serializedAdditionalRawData) { - FileId = fileId; + Name = name; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal CreateAssistantFileRequest() + /// Initializes a new instance of for deserialization. + internal ChatCompletionsFunctionToolSelection() { } - /// The ID of the previously uploaded file to attach. - public string FileId { get; } + /// The name of the function that should be called. + public string Name { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.Serialization.cs new file mode 100644 index 000000000000..86d957dcbc92 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsJsonResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsJsonResponseFormat)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsJsonResponseFormat 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(ChatCompletionsJsonResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsJsonResponseFormat(document.RootElement, options); + } + + internal static ChatCompletionsJsonResponseFormat DeserializeChatCompletionsJsonResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsJsonResponseFormat(type, serializedAdditionalRawData); + } + + 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(ChatCompletionsJsonResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsJsonResponseFormat 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 DeserializeChatCompletionsJsonResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsJsonResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsJsonResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsJsonResponseFormat(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.cs new file mode 100644 index 000000000000..f38d98e6fbd6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A response format for Chat Completions that restricts responses to emitting valid JSON objects. + public partial class ChatCompletionsJsonResponseFormat : ChatCompletionsResponseFormat + { + /// Initializes a new instance of . + public ChatCompletionsJsonResponseFormat() + { + Type = "json_object"; + } + + /// Initializes a new instance of . + /// The discriminated type for the response format. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsJsonResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.Serialization.cs new file mode 100644 index 000000000000..7d7884fc0d8b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsJsonSchemaResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsJsonSchemaResponseFormat)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("json_schema"u8); + writer.WriteObjectValue(JsonSchema, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsJsonSchemaResponseFormat 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(ChatCompletionsJsonSchemaResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsJsonSchemaResponseFormat(document.RootElement, options); + } + + internal static ChatCompletionsJsonSchemaResponseFormat DeserializeChatCompletionsJsonSchemaResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatCompletionsJsonSchemaResponseFormatJsonSchema jsonSchema = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("json_schema"u8)) + { + jsonSchema = ChatCompletionsJsonSchemaResponseFormatJsonSchema.DeserializeChatCompletionsJsonSchemaResponseFormatJsonSchema(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsJsonSchemaResponseFormat(type, serializedAdditionalRawData, jsonSchema); + } + + 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(ChatCompletionsJsonSchemaResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsJsonSchemaResponseFormat 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 DeserializeChatCompletionsJsonSchemaResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsJsonSchemaResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsJsonSchemaResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsJsonSchemaResponseFormat(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.cs new file mode 100644 index 000000000000..9892e885aba7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A response format for Chat Completions that restricts responses to emitting JSON that conforms to a provided JSON + /// Schema for Structured Outputs. + /// + public partial class ChatCompletionsJsonSchemaResponseFormat : ChatCompletionsResponseFormat + { + /// Initializes a new instance of . + /// + /// is null. + public ChatCompletionsJsonSchemaResponseFormat(ChatCompletionsJsonSchemaResponseFormatJsonSchema jsonSchema) + { + Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); + + Type = "json_schema"; + JsonSchema = jsonSchema; + } + + /// Initializes a new instance of . + /// The discriminated type for the response format. + /// Keeps track of any properties unknown to the library. + /// + internal ChatCompletionsJsonSchemaResponseFormat(string type, IDictionary serializedAdditionalRawData, ChatCompletionsJsonSchemaResponseFormatJsonSchema jsonSchema) : base(type, serializedAdditionalRawData) + { + JsonSchema = jsonSchema; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsJsonSchemaResponseFormat() + { + } + + /// Gets the json schema. + public ChatCompletionsJsonSchemaResponseFormatJsonSchema JsonSchema { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.Serialization.cs new file mode 100644 index 000000000000..c9dc99ddcff4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.Serialization.cs @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsJsonSchemaResponseFormatJsonSchema : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsJsonSchemaResponseFormatJsonSchema)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (Optional.IsDefined(Schema)) + { + writer.WritePropertyName("schema"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Schema); +#else + using (JsonDocument document = JsonDocument.Parse(Schema)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsDefined(Strict)) + { + if (Strict != null) + { + writer.WritePropertyName("strict"u8); + writer.WriteBooleanValue(Strict.Value); + } + else + { + writer.WriteNull("strict"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsJsonSchemaResponseFormatJsonSchema 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(ChatCompletionsJsonSchemaResponseFormatJsonSchema)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsJsonSchemaResponseFormatJsonSchema(document.RootElement, options); + } + + internal static ChatCompletionsJsonSchemaResponseFormatJsonSchema DeserializeChatCompletionsJsonSchemaResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string description = default; + string name = default; + BinaryData schema = default; + bool? strict = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("schema"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + schema = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("strict"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + strict = null; + continue; + } + strict = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsJsonSchemaResponseFormatJsonSchema(description, name, schema, strict, serializedAdditionalRawData); + } + + 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(ChatCompletionsJsonSchemaResponseFormatJsonSchema)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsJsonSchemaResponseFormatJsonSchema 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 DeserializeChatCompletionsJsonSchemaResponseFormatJsonSchema(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsJsonSchemaResponseFormatJsonSchema)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsJsonSchemaResponseFormatJsonSchema FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsJsonSchemaResponseFormatJsonSchema(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.cs new file mode 100644 index 000000000000..344920808c8c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The ChatCompletionsJsonSchemaResponseFormatJsonSchema. + public partial class ChatCompletionsJsonSchemaResponseFormatJsonSchema + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// is null. + public ChatCompletionsJsonSchemaResponseFormatJsonSchema(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + /// Initializes a new instance of . + /// A description of what the response format is for, used by the model to determine how to respond in the format. + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// + /// Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsJsonSchemaResponseFormatJsonSchema(string description, string name, BinaryData schema, bool? strict, IDictionary serializedAdditionalRawData) + { + Description = description; + Name = name; + Schema = schema; + Strict = strict; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsJsonSchemaResponseFormatJsonSchema() + { + } + + /// A description of what the response format is for, used by the model to determine how to respond in the format. + public string Description { get; set; } + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + public string Name { get; } + /// + /// Gets or sets the schema + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Schema { get; set; } + /// Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + public bool? Strict { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.Serialization.cs new file mode 100644 index 000000000000..78497714b92d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsNamedFunctionToolSelection : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsNamedFunctionToolSelection)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsNamedFunctionToolSelection 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(ChatCompletionsNamedFunctionToolSelection)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsNamedFunctionToolSelection(document.RootElement, options); + } + + internal static ChatCompletionsNamedFunctionToolSelection DeserializeChatCompletionsNamedFunctionToolSelection(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatCompletionsFunctionToolSelection function = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("function"u8)) + { + function = ChatCompletionsFunctionToolSelection.DeserializeChatCompletionsFunctionToolSelection(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsNamedFunctionToolSelection(type, serializedAdditionalRawData, function); + } + + 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(ChatCompletionsNamedFunctionToolSelection)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsNamedFunctionToolSelection 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 DeserializeChatCompletionsNamedFunctionToolSelection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsNamedFunctionToolSelection)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsNamedFunctionToolSelection FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsNamedFunctionToolSelection(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.cs new file mode 100644 index 000000000000..2645a6e5ad04 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A tool selection of a specific, named function tool that will limit chat completions to using the named function. + public partial class ChatCompletionsNamedFunctionToolSelection : ChatCompletionsNamedToolSelection + { + /// Initializes a new instance of . + /// The function that should be called. + /// is null. + public ChatCompletionsNamedFunctionToolSelection(ChatCompletionsFunctionToolSelection function) + { + Argument.AssertNotNull(function, nameof(function)); + + Type = "function"; + Function = function; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + /// The function that should be called. + internal ChatCompletionsNamedFunctionToolSelection(string type, IDictionary serializedAdditionalRawData, ChatCompletionsFunctionToolSelection function) : base(type, serializedAdditionalRawData) + { + Function = function; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsNamedFunctionToolSelection() + { + } + + /// The function that should be called. + public ChatCompletionsFunctionToolSelection Function { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.Serialization.cs new file mode 100644 index 000000000000..b9837419a4fa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatCompletionsNamedToolSelection))] + public partial class ChatCompletionsNamedToolSelection : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsNamedToolSelection)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsNamedToolSelection 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(ChatCompletionsNamedToolSelection)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsNamedToolSelection(document.RootElement, options); + } + + internal static ChatCompletionsNamedToolSelection DeserializeChatCompletionsNamedToolSelection(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "function": return ChatCompletionsNamedFunctionToolSelection.DeserializeChatCompletionsNamedFunctionToolSelection(element, options); + } + } + return UnknownChatCompletionsNamedToolSelection.DeserializeUnknownChatCompletionsNamedToolSelection(element, 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(ChatCompletionsNamedToolSelection)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsNamedToolSelection 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 DeserializeChatCompletionsNamedToolSelection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsNamedToolSelection)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsNamedToolSelection FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsNamedToolSelection(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.cs similarity index 55% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/ChatDataSource.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.cs index 35988a26e719..b25ed8fab461 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatDataSource.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -5,17 +8,14 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { /// - /// A representation of configuration data for a single Azure OpenAI chat data source. - /// This will be used by a chat completions request that should use Azure OpenAI chat extensions to augment the - /// response behavior. - /// The use of this configuration is compatible only with Azure OpenAI. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , , , and . + /// An abstract representation of an explicit, named tool selection to use for a chat completions request. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . /// - public abstract partial class ChatDataSource + public abstract partial class ChatCompletionsNamedToolSelection { /// /// Keeps track of any properties unknown to the library. @@ -47,22 +47,23 @@ public abstract partial class ChatDataSource /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - protected ChatDataSource() + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected ChatCompletionsNamedToolSelection() { } - /// Initializes a new instance of . - /// The differentiating type identifier for the data source. + /// Initializes a new instance of . + /// The object type. /// Keeps track of any properties unknown to the library. - internal ChatDataSource(string type, IDictionary serializedAdditionalRawData) + internal ChatCompletionsNamedToolSelection(string type, IDictionary serializedAdditionalRawData) { Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// The differentiating type identifier for the data source. + /// The object type. internal string Type { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.Serialization.cs new file mode 100644 index 000000000000..f6ce6ccd083f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.Serialization.cs @@ -0,0 +1,612 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("messages"u8); + writer.WriteStartArray(); + foreach (var item in Messages) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (Optional.IsCollectionDefined(Functions)) + { + writer.WritePropertyName("functions"u8); + writer.WriteStartArray(); + foreach (var item in Functions) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(FunctionCall)) + { + writer.WritePropertyName("function_call"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(FunctionCall); +#else + using (JsonDocument document = JsonDocument.Parse(FunctionCall)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsDefined(MaxTokens)) + { + writer.WritePropertyName("max_tokens"u8); + writer.WriteNumberValue(MaxTokens.Value); + } + if (Optional.IsDefined(MaxCompletionTokens)) + { + writer.WritePropertyName("max_completion_tokens"u8); + writer.WriteNumberValue(MaxCompletionTokens.Value); + } + if (Optional.IsDefined(Temperature)) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + if (Optional.IsDefined(NucleusSamplingFactor)) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(NucleusSamplingFactor.Value); + } + if (Optional.IsCollectionDefined(TokenSelectionBiases)) + { + writer.WritePropertyName("logit_bias"u8); + writer.WriteStartObject(); + foreach (var item in TokenSelectionBiases) + { + writer.WritePropertyName(item.Key); + writer.WriteNumberValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(User)) + { + writer.WritePropertyName("user"u8); + writer.WriteStringValue(User); + } + if (Optional.IsDefined(ChoiceCount)) + { + writer.WritePropertyName("n"u8); + writer.WriteNumberValue(ChoiceCount.Value); + } + if (Optional.IsCollectionDefined(StopSequences)) + { + writer.WritePropertyName("stop"u8); + writer.WriteStartArray(); + foreach (var item in StopSequences) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(PresencePenalty)) + { + writer.WritePropertyName("presence_penalty"u8); + writer.WriteNumberValue(PresencePenalty.Value); + } + if (Optional.IsDefined(FrequencyPenalty)) + { + writer.WritePropertyName("frequency_penalty"u8); + writer.WriteNumberValue(FrequencyPenalty.Value); + } + if (Optional.IsDefined(InternalShouldStreamResponse)) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(InternalShouldStreamResponse.Value); + } + if (Optional.IsDefined(StreamOptions)) + { + if (StreamOptions != null) + { + writer.WritePropertyName("stream_options"u8); + writer.WriteObjectValue(StreamOptions, options); + } + else + { + writer.WriteNull("stream_options"); + } + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + if (Optional.IsCollectionDefined(InternalAzureExtensionsDataSources)) + { + writer.WritePropertyName("data_sources"u8); + writer.WriteStartArray(); + foreach (var item in InternalAzureExtensionsDataSources) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Enhancements)) + { + writer.WritePropertyName("enhancements"u8); + writer.WriteObjectValue(Enhancements, options); + } + if (Optional.IsDefined(Seed)) + { + writer.WritePropertyName("seed"u8); + writer.WriteNumberValue(Seed.Value); + } + if (Optional.IsDefined(EnableLogProbabilities)) + { + if (EnableLogProbabilities != null) + { + writer.WritePropertyName("logprobs"u8); + writer.WriteBooleanValue(EnableLogProbabilities.Value); + } + else + { + writer.WriteNull("logprobs"); + } + } + if (Optional.IsDefined(LogProbabilitiesPerToken)) + { + if (LogProbabilitiesPerToken != null) + { + writer.WritePropertyName("top_logprobs"u8); + writer.WriteNumberValue(LogProbabilitiesPerToken.Value); + } + else + { + writer.WriteNull("top_logprobs"); + } + } + if (Optional.IsDefined(ResponseFormat)) + { + writer.WritePropertyName("response_format"u8); + writer.WriteObjectValue(ResponseFormat, options); + } + if (Optional.IsCollectionDefined(Tools)) + { + writer.WritePropertyName("tools"u8); + writer.WriteStartArray(); + foreach (var item in Tools) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(ToolChoice)) + { + writer.WritePropertyName("tool_choice"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ToolChoice); +#else + using (JsonDocument document = JsonDocument.Parse(ToolChoice)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsDefined(ParallelToolCalls)) + { + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(ParallelToolCalls.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsOptions 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(ChatCompletionsOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsOptions(document.RootElement, options); + } + + internal static ChatCompletionsOptions DeserializeChatCompletionsOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList messages = default; + IList functions = default; + BinaryData functionCall = default; + int? maxTokens = default; + int? maxCompletionTokens = default; + float? temperature = default; + float? topP = default; + IDictionary logitBias = default; + string user = default; + int? n = default; + IList stop = default; + float? presencePenalty = default; + float? frequencyPenalty = default; + bool? stream = default; + ChatCompletionStreamOptions streamOptions = default; + string model = default; + IList dataSources = default; + AzureChatEnhancementConfiguration enhancements = default; + long? seed = default; + bool? logprobs = default; + int? topLogprobs = default; + ChatCompletionsResponseFormat responseFormat = default; + IList tools = default; + BinaryData toolChoice = default; + bool? parallelToolCalls = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("messages"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatRequestMessage.DeserializeChatRequestMessage(item, options)); + } + messages = array; + continue; + } + if (property.NameEquals("functions"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(FunctionDefinition.DeserializeFunctionDefinition(item, options)); + } + functions = array; + continue; + } + if (property.NameEquals("function_call"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + functionCall = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("max_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_completion_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxCompletionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("logit_bias"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetInt32()); + } + logitBias = dictionary; + continue; + } + if (property.NameEquals("user"u8)) + { + user = property.Value.GetString(); + continue; + } + if (property.NameEquals("n"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + n = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("stop"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + stop = array; + continue; + } + if (property.NameEquals("presence_penalty"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + presencePenalty = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("frequency_penalty"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + frequencyPenalty = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("stream"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stream = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stream_options"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + streamOptions = null; + continue; + } + streamOptions = ChatCompletionStreamOptions.DeserializeChatCompletionStreamOptions(property.Value, options); + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (property.NameEquals("data_sources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureChatExtensionConfiguration.DeserializeAzureChatExtensionConfiguration(item, options)); + } + dataSources = array; + continue; + } + if (property.NameEquals("enhancements"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + enhancements = AzureChatEnhancementConfiguration.DeserializeAzureChatEnhancementConfiguration(property.Value, options); + continue; + } + if (property.NameEquals("seed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + seed = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + logprobs = null; + continue; + } + logprobs = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("top_logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topLogprobs = null; + continue; + } + topLogprobs = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = ChatCompletionsResponseFormat.DeserializeChatCompletionsResponseFormat(property.Value, options); + continue; + } + if (property.NameEquals("tools"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatCompletionsToolDefinition.DeserializeChatCompletionsToolDefinition(item, options)); + } + tools = array; + continue; + } + if (property.NameEquals("tool_choice"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + toolChoice = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("parallel_tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parallelToolCalls = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsOptions( + messages, + functions ?? new ChangeTrackingList(), + functionCall, + maxTokens, + maxCompletionTokens, + temperature, + topP, + logitBias ?? new ChangeTrackingDictionary(), + user, + n, + stop ?? new ChangeTrackingList(), + presencePenalty, + frequencyPenalty, + stream, + streamOptions, + model, + dataSources ?? new ChangeTrackingList(), + enhancements, + seed, + logprobs, + topLogprobs, + responseFormat, + tools ?? new ChangeTrackingList(), + toolChoice, + parallelToolCalls, + serializedAdditionalRawData); + } + + 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(ChatCompletionsOptions)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsOptions 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 DeserializeChatCompletionsOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.cs new file mode 100644 index 000000000000..3d1ebd1135d1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.cs @@ -0,0 +1,414 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// The configuration information for a chat completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + public partial class ChatCompletionsOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// The collection of context messages associated with this chat completions request. + /// Typical usage begins with a chat message for the System role that provides instructions for + /// the behavior of the assistant, followed by alternating messages between the User and + /// Assistant roles. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + /// is null. + public ChatCompletionsOptions(IEnumerable messages) + { + Argument.AssertNotNull(messages, nameof(messages)); + + Messages = messages.ToList(); + Functions = new ChangeTrackingList(); + TokenSelectionBiases = new ChangeTrackingDictionary(); + StopSequences = new ChangeTrackingList(); + InternalAzureExtensionsDataSources = new ChangeTrackingList(); + Tools = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// + /// The collection of context messages associated with this chat completions request. + /// Typical usage begins with a chat message for the System role that provides instructions for + /// the behavior of the assistant, followed by alternating messages between the User and + /// Assistant roles. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + /// A list of functions the model may generate JSON inputs for. + /// + /// Controls how the model responds to function calls. "none" means the model does not call a function, + /// and responds to the end-user. "auto" means the model can pick between an end-user or calling a function. + /// Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + /// "none" is the default when no functions are present. "auto" is the default if functions are present. + /// + /// + /// The maximum number of tokens allowed for the generated answer. By default, the number of tokens the model can return will be (4096 - prompt tokens). + /// + /// This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with o1 series models. + /// + /// An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and reasoning tokens. + /// + /// The sampling temperature to use that controls the apparent creativity of generated completions. + /// Higher values will make output more random while lower values will make results more focused + /// and deterministic. + /// It is not recommended to modify temperature and top_p for the same completions request as the + /// interaction of these two settings is difficult to predict. + /// + /// + /// An alternative to sampling with temperature called nucleus sampling. This value causes the + /// model to consider the results of tokens with the provided probability mass. As an example, a + /// value of 0.15 will cause only the tokens comprising the top 15% of probability mass to be + /// considered. + /// It is not recommended to modify temperature and top_p for the same completions request as the + /// interaction of these two settings is difficult to predict. + /// + /// + /// A map between GPT token IDs and bias scores that influences the probability of specific tokens + /// appearing in a completions response. Token IDs are computed via external tokenizer tools, while + /// bias scores reside in the range of -100 to 100 with minimum and maximum values corresponding to + /// a full ban or exclusive selection of a token, respectively. The exact behavior of a given bias + /// score varies by model. + /// + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + /// + /// The number of chat completions choices that should be generated for a chat completions + /// response. + /// Because this setting can generate many completions, it may quickly consume your token quota. + /// Use carefully and ensure reasonable settings for max_tokens and stop. + /// + /// A collection of textual sequences that will end completions generation. + /// + /// A value that influences the probability of generated tokens appearing based on their existing + /// presence in generated text. + /// Positive values will make tokens less likely to appear when they already exist and increase the + /// model's likelihood to output new topics. + /// + /// + /// A value that influences the probability of generated tokens appearing based on their cumulative + /// frequency in generated text. + /// Positive values will make tokens less likely to appear as their frequency increases and + /// decrease the likelihood of the model repeating the same statements verbatim. + /// + /// A value indicating whether chat completions should be streamed for this request. + /// Options for streaming response. Only set this when you set `stream: true`. + /// + /// The model name to provide as part of this completions request. + /// Not applicable to Azure OpenAI, where deployment information should be included in the Azure + /// resource URI that's connected to. + /// + /// + /// The configuration entries for Azure OpenAI chat extensions that use them. + /// This additional specification is only compatible with Azure OpenAI. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + /// If provided, the configuration options for available Azure OpenAI chat enhancements. + /// + /// If specified, the system will make a best effort to sample deterministically such that repeated requests with the + /// same seed and parameters should return the same result. Determinism is not guaranteed, and you should refer to the + /// system_fingerprint response parameter to monitor changes in the backend." + /// + /// Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. This option is currently not available on the `gpt-4-vision-preview` model. + /// An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. + /// + /// An object specifying the format that the model must output. Used to enable JSON mode. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + /// + /// The available tool definitions that the chat completions request can use, including caller-defined functions. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// If specified, the model will configure which of the provided tools it can use for the chat completions response. + /// Whether to enable parallel function calling during tool use. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsOptions(IList messages, IList functions, BinaryData functionCall, int? maxTokens, int? maxCompletionTokens, float? temperature, float? nucleusSamplingFactor, IDictionary tokenSelectionBiases, string user, int? choiceCount, IList stopSequences, float? presencePenalty, float? frequencyPenalty, bool? internalShouldStreamResponse, ChatCompletionStreamOptions streamOptions, string deploymentName, IList internalAzureExtensionsDataSources, AzureChatEnhancementConfiguration enhancements, long? seed, bool? enableLogProbabilities, int? logProbabilitiesPerToken, ChatCompletionsResponseFormat responseFormat, IList tools, BinaryData toolChoice, bool? parallelToolCalls, IDictionary serializedAdditionalRawData) + { + Messages = messages; + Functions = functions; + FunctionCall = functionCall; + MaxTokens = maxTokens; + MaxCompletionTokens = maxCompletionTokens; + Temperature = temperature; + NucleusSamplingFactor = nucleusSamplingFactor; + TokenSelectionBiases = tokenSelectionBiases; + User = user; + ChoiceCount = choiceCount; + StopSequences = stopSequences; + PresencePenalty = presencePenalty; + FrequencyPenalty = frequencyPenalty; + InternalShouldStreamResponse = internalShouldStreamResponse; + StreamOptions = streamOptions; + DeploymentName = deploymentName; + InternalAzureExtensionsDataSources = internalAzureExtensionsDataSources; + Enhancements = enhancements; + Seed = seed; + EnableLogProbabilities = enableLogProbabilities; + LogProbabilitiesPerToken = logProbabilitiesPerToken; + ResponseFormat = responseFormat; + Tools = tools; + ToolChoice = toolChoice; + ParallelToolCalls = parallelToolCalls; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsOptions() + { + } + + /// + /// The collection of context messages associated with this chat completions request. + /// Typical usage begins with a chat message for the System role that provides instructions for + /// the behavior of the assistant, followed by alternating messages between the User and + /// Assistant roles. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + public IList Messages { get; } + /// A list of functions the model may generate JSON inputs for. + public IList Functions { get; } + /// + /// Controls how the model responds to function calls. "none" means the model does not call a function, + /// and responds to the end-user. "auto" means the model can pick between an end-user or calling a function. + /// Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. + /// "none" is the default when no functions are present. "auto" is the default if functions are present. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData FunctionCall { get; set; } + /// + /// The maximum number of tokens allowed for the generated answer. By default, the number of tokens the model can return will be (4096 - prompt tokens). + /// + /// This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with o1 series models. + /// + public int? MaxTokens { get; set; } + /// An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and reasoning tokens. + public int? MaxCompletionTokens { get; set; } + /// + /// The sampling temperature to use that controls the apparent creativity of generated completions. + /// Higher values will make output more random while lower values will make results more focused + /// and deterministic. + /// It is not recommended to modify temperature and top_p for the same completions request as the + /// interaction of these two settings is difficult to predict. + /// + public float? Temperature { get; set; } + /// + /// An alternative to sampling with temperature called nucleus sampling. This value causes the + /// model to consider the results of tokens with the provided probability mass. As an example, a + /// value of 0.15 will cause only the tokens comprising the top 15% of probability mass to be + /// considered. + /// It is not recommended to modify temperature and top_p for the same completions request as the + /// interaction of these two settings is difficult to predict. + /// + public float? NucleusSamplingFactor { get; set; } + /// + /// A map between GPT token IDs and bias scores that influences the probability of specific tokens + /// appearing in a completions response. Token IDs are computed via external tokenizer tools, while + /// bias scores reside in the range of -100 to 100 with minimum and maximum values corresponding to + /// a full ban or exclusive selection of a token, respectively. The exact behavior of a given bias + /// score varies by model. + /// + public IDictionary TokenSelectionBiases { get; } + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + public string User { get; set; } + /// + /// The number of chat completions choices that should be generated for a chat completions + /// response. + /// Because this setting can generate many completions, it may quickly consume your token quota. + /// Use carefully and ensure reasonable settings for max_tokens and stop. + /// + public int? ChoiceCount { get; set; } + /// A collection of textual sequences that will end completions generation. + public IList StopSequences { get; } + /// + /// A value that influences the probability of generated tokens appearing based on their existing + /// presence in generated text. + /// Positive values will make tokens less likely to appear when they already exist and increase the + /// model's likelihood to output new topics. + /// + public float? PresencePenalty { get; set; } + /// + /// A value that influences the probability of generated tokens appearing based on their cumulative + /// frequency in generated text. + /// Positive values will make tokens less likely to appear as their frequency increases and + /// decrease the likelihood of the model repeating the same statements verbatim. + /// + public float? FrequencyPenalty { get; set; } + /// A value indicating whether chat completions should be streamed for this request. + public bool? InternalShouldStreamResponse { get; set; } + /// Options for streaming response. Only set this when you set `stream: true`. + public ChatCompletionStreamOptions StreamOptions { get; set; } + /// + /// The model name to provide as part of this completions request. + /// Not applicable to Azure OpenAI, where deployment information should be included in the Azure + /// resource URI that's connected to. + /// + public string DeploymentName { get; set; } + /// + /// The configuration entries for Azure OpenAI chat extensions that use them. + /// This additional specification is only compatible with Azure OpenAI. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + public IList InternalAzureExtensionsDataSources { get; } + /// If provided, the configuration options for available Azure OpenAI chat enhancements. + public AzureChatEnhancementConfiguration Enhancements { get; set; } + /// + /// If specified, the system will make a best effort to sample deterministically such that repeated requests with the + /// same seed and parameters should return the same result. Determinism is not guaranteed, and you should refer to the + /// system_fingerprint response parameter to monitor changes in the backend." + /// + public long? Seed { get; set; } + /// Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. This option is currently not available on the `gpt-4-vision-preview` model. + public bool? EnableLogProbabilities { get; set; } + /// An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. + public int? LogProbabilitiesPerToken { get; set; } + /// + /// An object specifying the format that the model must output. Used to enable JSON mode. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public ChatCompletionsResponseFormat ResponseFormat { get; set; } + /// + /// The available tool definitions that the chat completions request can use, including caller-defined functions. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public IList Tools { get; } + /// + /// If specified, the model will configure which of the provided tools it can use for the chat completions response. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ToolChoice { get; set; } + /// Whether to enable parallel function calling during tool use. + public bool? ParallelToolCalls { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.Serialization.cs new file mode 100644 index 000000000000..8f973150e68e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.Serialization.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatCompletionsResponseFormat))] + public partial class ChatCompletionsResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsResponseFormat)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsResponseFormat 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(ChatCompletionsResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsResponseFormat(document.RootElement, options); + } + + internal static ChatCompletionsResponseFormat DeserializeChatCompletionsResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "json_object": return ChatCompletionsJsonResponseFormat.DeserializeChatCompletionsJsonResponseFormat(element, options); + case "json_schema": return ChatCompletionsJsonSchemaResponseFormat.DeserializeChatCompletionsJsonSchemaResponseFormat(element, options); + case "text": return ChatCompletionsTextResponseFormat.DeserializeChatCompletionsTextResponseFormat(element, options); + } + } + return UnknownChatCompletionsResponseFormat.DeserializeUnknownChatCompletionsResponseFormat(element, 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(ChatCompletionsResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsResponseFormat 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 DeserializeChatCompletionsResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsResponseFormat(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.cs new file mode 100644 index 000000000000..43211d2ed3cb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a response format configuration usable by Chat Completions. Can be used to enable JSON + /// mode. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public abstract partial class ChatCompletionsResponseFormat + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected ChatCompletionsResponseFormat() + { + } + + /// Initializes a new instance of . + /// The discriminated type for the response format. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsResponseFormat(string type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The discriminated type for the response format. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.Serialization.cs new file mode 100644 index 000000000000..d02053e70918 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsTextResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsTextResponseFormat)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsTextResponseFormat 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(ChatCompletionsTextResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsTextResponseFormat(document.RootElement, options); + } + + internal static ChatCompletionsTextResponseFormat DeserializeChatCompletionsTextResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsTextResponseFormat(type, serializedAdditionalRawData); + } + + 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(ChatCompletionsTextResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsTextResponseFormat 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 DeserializeChatCompletionsTextResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsTextResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsTextResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsTextResponseFormat(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.cs new file mode 100644 index 000000000000..d1bf93c195ba --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response + /// content that adheres to a specific schema. + /// + public partial class ChatCompletionsTextResponseFormat : ChatCompletionsResponseFormat + { + /// Initializes a new instance of . + public ChatCompletionsTextResponseFormat() + { + Type = "text"; + } + + /// Initializes a new instance of . + /// The discriminated type for the response format. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsTextResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.Serialization.cs new file mode 100644 index 000000000000..2f22962c93e7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.Serialization.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatCompletionsToolCall))] + public partial class ChatCompletionsToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsToolCall)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsToolCall 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(ChatCompletionsToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsToolCall(document.RootElement, options); + } + + internal static ChatCompletionsToolCall DeserializeChatCompletionsToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "function": return ChatCompletionsFunctionToolCall.DeserializeChatCompletionsFunctionToolCall(element, options); + } + } + return UnknownChatCompletionsToolCall.DeserializeUnknownChatCompletionsToolCall(element, 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(ChatCompletionsToolCall)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsToolCall 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 DeserializeChatCompletionsToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsToolCall(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.cs new file mode 100644 index 000000000000..a6de3a467520 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a tool call that must be resolved in a subsequent request to perform the requested + /// chat completion. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public abstract partial class ChatCompletionsToolCall + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ID of the tool call. + /// is null. + protected ChatCompletionsToolCall(string id) + { + Argument.AssertNotNull(id, nameof(id)); + + Id = id; + } + + /// Initializes a new instance of . + /// The object type. + /// The ID of the tool call. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsToolCall(string type, string id, IDictionary serializedAdditionalRawData) + { + Type = type; + Id = id; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsToolCall() + { + } + + /// The object type. + internal string Type { get; set; } + /// The ID of the tool call. + public string Id { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.Serialization.cs new file mode 100644 index 000000000000..d084f95cff6e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatCompletionsToolDefinition))] + public partial class ChatCompletionsToolDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsToolDefinition)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsToolDefinition 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(ChatCompletionsToolDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsToolDefinition(document.RootElement, options); + } + + internal static ChatCompletionsToolDefinition DeserializeChatCompletionsToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "function": return ChatCompletionsFunctionToolDefinition.DeserializeChatCompletionsFunctionToolDefinition(element, options); + } + } + return UnknownChatCompletionsToolDefinition.DeserializeUnknownChatCompletionsToolDefinition(element, 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(ChatCompletionsToolDefinition)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsToolDefinition 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 DeserializeChatCompletionsToolDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsToolDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsToolDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatCompletionsToolDefinition(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceAuthentication.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.cs similarity index 56% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceAuthentication.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.cs index 60914d91a96c..712c79c1aeb9 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceAuthentication.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -5,13 +8,14 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { /// - /// The AzureChatDataSourceAuthenticationOptions. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. + /// An abstract representation of a tool that can be used by the model to improve a chat completions response. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . /// - public abstract partial class DataSourceAuthentication + public abstract partial class ChatCompletionsToolDefinition { /// /// Keeps track of any properties unknown to the library. @@ -43,22 +47,23 @@ public abstract partial class DataSourceAuthentication /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - protected DataSourceAuthentication() + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected ChatCompletionsToolDefinition() { } - /// Initializes a new instance of . - /// Discriminator. + /// Initializes a new instance of . + /// The object type. /// Keeps track of any properties unknown to the library. - internal DataSourceAuthentication(string type, IDictionary serializedAdditionalRawData) + internal ChatCompletionsToolDefinition(string type, IDictionary serializedAdditionalRawData) { Type = type; - SerializedAdditionalRawData = serializedAdditionalRawData; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Discriminator. + /// The object type. internal string Type { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolSelectionPreset.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolSelectionPreset.cs new file mode 100644 index 000000000000..9916c3d6a74b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolSelectionPreset.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Represents a generic policy for how a chat completions tool may be selected. + public readonly partial struct ChatCompletionsToolSelectionPreset : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ChatCompletionsToolSelectionPreset(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string NoneValue = "none"; + private const string RequiredValue = "required"; + + /// + /// Specifies that the model may either use any of the tools provided in this chat completions request or + /// instead return a standard chat completions response as if no tools were provided. + /// + public static ChatCompletionsToolSelectionPreset Auto { get; } = new ChatCompletionsToolSelectionPreset(AutoValue); + /// + /// Specifies that the model should not respond with a tool call and should instead provide a standard chat + /// completions response. Response content may still be influenced by the provided tool definitions. + /// + public static ChatCompletionsToolSelectionPreset None { get; } = new ChatCompletionsToolSelectionPreset(NoneValue); + /// Specifies that the model must call one or more tools. + public static ChatCompletionsToolSelectionPreset Required { get; } = new ChatCompletionsToolSelectionPreset(RequiredValue); + /// Determines if two values are the same. + public static bool operator ==(ChatCompletionsToolSelectionPreset left, ChatCompletionsToolSelectionPreset right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ChatCompletionsToolSelectionPreset left, ChatCompletionsToolSelectionPreset right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ChatCompletionsToolSelectionPreset(string value) => new ChatCompletionsToolSelectionPreset(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ChatCompletionsToolSelectionPreset other && Equals(other); + /// + public bool Equals(ChatCompletionsToolSelectionPreset other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatDataSource.Serialization.cs deleted file mode 100644 index 78dc642677f4..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatDataSource.Serialization.cs +++ /dev/null @@ -1,130 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - [PersistableModelProxy(typeof(InternalUnknownAzureChatDataSource))] - public partial class ChatDataSource : 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(ChatDataSource)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - ChatDataSource 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(ChatDataSource)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatDataSource(document.RootElement, options); - } - - internal static ChatDataSource DeserializeChatDataSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - if (element.TryGetProperty("type", out JsonElement discriminator)) - { - switch (discriminator.GetString()) - { - case "azure_cosmos_db": return CosmosChatDataSource.DeserializeCosmosChatDataSource(element, options); - case "azure_search": return AzureSearchChatDataSource.DeserializeAzureSearchChatDataSource(element, options); - case "elasticsearch": return ElasticsearchChatDataSource.DeserializeElasticsearchChatDataSource(element, options); - case "mongo_db": return MongoDBChatDataSource.DeserializeMongoDBChatDataSource(element, options); - case "pinecone": return PineconeChatDataSource.DeserializePineconeChatDataSource(element, options); - } - } - return InternalUnknownAzureChatDataSource.DeserializeInternalUnknownAzureChatDataSource(element, 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(ChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - ChatDataSource 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 DeserializeChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ChatDataSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatDataSource(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatDocumentFilterReason.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatDocumentFilterReason.cs deleted file mode 100644 index 798da3e6725d..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatDocumentFilterReason.cs +++ /dev/null @@ -1,48 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureChatMessageContextAllRetrievedDocumentsFilterReason. - public readonly partial struct ChatDocumentFilterReason : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public ChatDocumentFilterReason(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ScoreValue = "score"; - private const string RerankValue = "rerank"; - - /// score. - public static ChatDocumentFilterReason Score { get; } = new ChatDocumentFilterReason(ScoreValue); - /// rerank. - public static ChatDocumentFilterReason Rerank { get; } = new ChatDocumentFilterReason(RerankValue); - /// Determines if two values are the same. - public static bool operator ==(ChatDocumentFilterReason left, ChatDocumentFilterReason right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(ChatDocumentFilterReason left, ChatDocumentFilterReason right) => !left.Equals(right); - /// Converts a string to a . - public static implicit operator ChatDocumentFilterReason(string value) => new ChatDocumentFilterReason(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ChatDocumentFilterReason other && Equals(other); - /// - public bool Equals(ChatDocumentFilterReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.Serialization.cs new file mode 100644 index 000000000000..606882908417 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.Serialization.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatMessageContentItem))] + public partial class ChatMessageContentItem : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatMessageContentItem)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatMessageContentItem 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(ChatMessageContentItem)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageContentItem(document.RootElement, options); + } + + internal static ChatMessageContentItem DeserializeChatMessageContentItem(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "image_url": return ChatMessageImageContentItem.DeserializeChatMessageImageContentItem(element, options); + case "refusal": return ChatMessageRefusalContentItem.DeserializeChatMessageRefusalContentItem(element, options); + case "text": return ChatMessageTextContentItem.DeserializeChatMessageTextContentItem(element, options); + } + } + return UnknownChatMessageContentItem.DeserializeUnknownChatMessageContentItem(element, 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(ChatMessageContentItem)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageContentItem 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 DeserializeChatMessageContentItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatMessageContentItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatMessageContentItem(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.cs new file mode 100644 index 000000000000..40a3f4f1679c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a structured content item within a chat message. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public abstract partial class ChatMessageContentItem + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected ChatMessageContentItem() + { + } + + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + internal ChatMessageContentItem(string type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The discriminated object type. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContext.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContext.Serialization.cs deleted file mode 100644 index 7d8cab801548..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContext.Serialization.cs +++ /dev/null @@ -1,176 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - public partial class ChatMessageContext : 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(ChatMessageContext)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("intent") != true && Optional.IsDefined(Intent)) - { - writer.WritePropertyName("intent"u8); - writer.WriteStringValue(Intent); - } - if (SerializedAdditionalRawData?.ContainsKey("citations") != true && Optional.IsCollectionDefined(Citations)) - { - writer.WritePropertyName("citations"u8); - writer.WriteStartArray(); - foreach (var item in Citations) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (SerializedAdditionalRawData?.ContainsKey("all_retrieved_documents") != true && Optional.IsDefined(RetrievedDocuments)) - { - writer.WritePropertyName("all_retrieved_documents"u8); - writer.WriteObjectValue(RetrievedDocuments, 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(); - } - - ChatMessageContext 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(ChatMessageContext)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatMessageContext(document.RootElement, options); - } - - internal static ChatMessageContext DeserializeChatMessageContext(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string intent = default; - IReadOnlyList citations = default; - ChatRetrievedDocument allRetrievedDocuments = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("intent"u8)) - { - intent = property.Value.GetString(); - continue; - } - if (property.NameEquals("citations"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(ChatCitation.DeserializeChatCitation(item, options)); - } - citations = array; - continue; - } - if (property.NameEquals("all_retrieved_documents"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - allRetrievedDocuments = ChatRetrievedDocument.DeserializeChatRetrievedDocument(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ChatMessageContext(intent, citations ?? new ChangeTrackingList(), allRetrievedDocuments, serializedAdditionalRawData); - } - - 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(ChatMessageContext)} does not support writing '{options.Format}' format."); - } - } - - ChatMessageContext 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 DeserializeChatMessageContext(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ChatMessageContext)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ChatMessageContext FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeChatMessageContext(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContext.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContext.cs deleted file mode 100644 index 7a117a45cbe4..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContext.cs +++ /dev/null @@ -1,71 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// - /// An additional property, added to chat completion response messages, produced by the Azure OpenAI service when using - /// extension behavior. This includes intent and citation information from the On Your Data feature. - /// - public partial class ChatMessageContext - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal ChatMessageContext() - { - Citations = new ChangeTrackingList(); - } - - /// Initializes a new instance of . - /// The detected intent from the chat history, which is used to carry conversation context between interactions. - /// The citations produced by the data retrieval. - /// Summary information about documents retrieved by the data retrieval operation. - /// Keeps track of any properties unknown to the library. - internal ChatMessageContext(string intent, IReadOnlyList citations, ChatRetrievedDocument retrievedDocuments, IDictionary serializedAdditionalRawData) - { - Intent = intent; - Citations = citations; - RetrievedDocuments = retrievedDocuments; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The detected intent from the chat history, which is used to carry conversation context between interactions. - public string Intent { get; } - /// The citations produced by the data retrieval. - public IReadOnlyList Citations { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.Serialization.cs new file mode 100644 index 000000000000..d36671902ae9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatMessageImageContentItem : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatMessageImageContentItem)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("image_url"u8); + writer.WriteObjectValue(ImageUrl, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatMessageImageContentItem 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(ChatMessageImageContentItem)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageImageContentItem(document.RootElement, options); + } + + internal static ChatMessageImageContentItem DeserializeChatMessageImageContentItem(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatMessageImageUrl imageUrl = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("image_url"u8)) + { + imageUrl = ChatMessageImageUrl.DeserializeChatMessageImageUrl(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatMessageImageContentItem(type, serializedAdditionalRawData, imageUrl); + } + + 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(ChatMessageImageContentItem)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageImageContentItem 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 DeserializeChatMessageImageContentItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageImageContentItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatMessageImageContentItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatMessageImageContentItem(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.cs new file mode 100644 index 000000000000..69aaa3ec3cea --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A structured chat content item containing an image reference. + public partial class ChatMessageImageContentItem : ChatMessageContentItem + { + /// Initializes a new instance of . + /// An internet location, which must be accessible to the model,from which the image may be retrieved. + /// is null. + public ChatMessageImageContentItem(ChatMessageImageUrl imageUrl) + { + Argument.AssertNotNull(imageUrl, nameof(imageUrl)); + + Type = "image_url"; + ImageUrl = imageUrl; + } + + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + /// An internet location, which must be accessible to the model,from which the image may be retrieved. + internal ChatMessageImageContentItem(string type, IDictionary serializedAdditionalRawData, ChatMessageImageUrl imageUrl) : base(type, serializedAdditionalRawData) + { + ImageUrl = imageUrl; + } + + /// Initializes a new instance of for deserialization. + internal ChatMessageImageContentItem() + { + } + + /// An internet location, which must be accessible to the model,from which the image may be retrieved. + public ChatMessageImageUrl ImageUrl { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageDetailLevel.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageDetailLevel.cs new file mode 100644 index 000000000000..bc0649288b24 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageDetailLevel.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// A representation of the possible image detail levels for image-based chat completions message content. + public readonly partial struct ChatMessageImageDetailLevel : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ChatMessageImageDetailLevel(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string LowValue = "low"; + private const string HighValue = "high"; + + /// Specifies that the model should determine which detail level to apply using heuristics like image size. + public static ChatMessageImageDetailLevel Auto { get; } = new ChatMessageImageDetailLevel(AutoValue); + /// + /// Specifies that image evaluation should be constrained to the 'low-res' model that may be faster and consume fewer + /// tokens but may also be less accurate for highly detailed images. + /// + public static ChatMessageImageDetailLevel Low { get; } = new ChatMessageImageDetailLevel(LowValue); + /// + /// Specifies that image evaluation should enable the 'high-res' model that may be more accurate for highly detailed + /// images but may also be slower and consume more tokens. + /// + public static ChatMessageImageDetailLevel High { get; } = new ChatMessageImageDetailLevel(HighValue); + /// Determines if two values are the same. + public static bool operator ==(ChatMessageImageDetailLevel left, ChatMessageImageDetailLevel right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ChatMessageImageDetailLevel left, ChatMessageImageDetailLevel right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ChatMessageImageDetailLevel(string value) => new ChatMessageImageDetailLevel(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ChatMessageImageDetailLevel other && Equals(other); + /// + public bool Equals(ChatMessageImageDetailLevel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.Serialization.cs new file mode 100644 index 000000000000..30b9e1fe377f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatMessageImageUrl : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatMessageImageUrl)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("url"u8); + writer.WriteStringValue(Url.AbsoluteUri); + if (Optional.IsDefined(Detail)) + { + writer.WritePropertyName("detail"u8); + writer.WriteStringValue(Detail.Value.ToString()); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatMessageImageUrl 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(ChatMessageImageUrl)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageImageUrl(document.RootElement, options); + } + + internal static ChatMessageImageUrl DeserializeChatMessageImageUrl(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Uri url = default; + ChatMessageImageDetailLevel? detail = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("url"u8)) + { + url = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("detail"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + detail = new ChatMessageImageDetailLevel(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatMessageImageUrl(url, detail, serializedAdditionalRawData); + } + + 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(ChatMessageImageUrl)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageImageUrl 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 DeserializeChatMessageImageUrl(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageImageUrl)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatMessageImageUrl FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatMessageImageUrl(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.cs new file mode 100644 index 000000000000..ccccaecc34cb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// An internet location from which the model may retrieve an image. + public partial class ChatMessageImageUrl + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The URL of the image. + /// is null. + public ChatMessageImageUrl(Uri url) + { + Argument.AssertNotNull(url, nameof(url)); + + Url = url; + } + + /// Initializes a new instance of . + /// The URL of the image. + /// + /// The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and + /// accuracy. + /// + /// Keeps track of any properties unknown to the library. + internal ChatMessageImageUrl(Uri url, ChatMessageImageDetailLevel? detail, IDictionary serializedAdditionalRawData) + { + Url = url; + Detail = detail; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatMessageImageUrl() + { + } + + /// The URL of the image. + public Uri Url { get; } + /// + /// The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and + /// accuracy. + /// + public ChatMessageImageDetailLevel? Detail { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.Serialization.cs new file mode 100644 index 000000000000..cd16b05ca749 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatMessageRefusalContentItem : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatMessageRefusalContentItem)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatMessageRefusalContentItem 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(ChatMessageRefusalContentItem)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageRefusalContentItem(document.RootElement, options); + } + + internal static ChatMessageRefusalContentItem DeserializeChatMessageRefusalContentItem(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string refusal = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("refusal"u8)) + { + refusal = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatMessageRefusalContentItem(type, serializedAdditionalRawData, refusal); + } + + 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(ChatMessageRefusalContentItem)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageRefusalContentItem 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 DeserializeChatMessageRefusalContentItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageRefusalContentItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatMessageRefusalContentItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatMessageRefusalContentItem(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.cs new file mode 100644 index 000000000000..676b07fb5c85 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A structured chat content item containing model refusal information for a structured outputs request. + public partial class ChatMessageRefusalContentItem : ChatMessageContentItem + { + /// Initializes a new instance of . + /// The refusal message. + /// is null. + public ChatMessageRefusalContentItem(string refusal) + { + Argument.AssertNotNull(refusal, nameof(refusal)); + + Type = "refusal"; + Refusal = refusal; + } + + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + /// The refusal message. + internal ChatMessageRefusalContentItem(string type, IDictionary serializedAdditionalRawData, string refusal) : base(type, serializedAdditionalRawData) + { + Refusal = refusal; + } + + /// Initializes a new instance of for deserialization. + internal ChatMessageRefusalContentItem() + { + } + + /// The refusal message. + public string Refusal { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.Serialization.cs similarity index 61% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.Serialization.cs index 3abf92d075f2..d67cb537d29f 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.Serialization.cs @@ -11,23 +11,25 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.OpenAI.Assistants +namespace Azure.AI.OpenAI { - internal partial class CreateAssistantFileRequest : IUtf8JsonSerializable, IJsonModel + public partial class ChatMessageTextContentItem : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(CreateAssistantFileRequest)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ChatMessageTextContentItem)} does not support writing '{format}' format."); } writer.WriteStartObject(); - writer.WritePropertyName("file_id"u8); - writer.WriteStringValue(FileId); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -46,19 +48,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe writer.WriteEndObject(); } - CreateAssistantFileRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatMessageTextContentItem 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(CreateAssistantFileRequest)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatMessageTextContentItem)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateAssistantFileRequest(document.RootElement, options); + return DeserializeChatMessageTextContentItem(document.RootElement, options); } - internal static CreateAssistantFileRequest DeserializeCreateAssistantFileRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static ChatMessageTextContentItem DeserializeChatMessageTextContentItem(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -66,14 +68,20 @@ internal static CreateAssistantFileRequest DeserializeCreateAssistantFileRequest { return null; } - string fileId = default; + string text = default; + string type = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (property.NameEquals("text"u8)) { - fileId = property.Value.GetString(); + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); continue; } if (options.Format != "W") @@ -82,50 +90,50 @@ internal static CreateAssistantFileRequest DeserializeCreateAssistantFileRequest } } serializedAdditionalRawData = rawDataDictionary; - return new CreateAssistantFileRequest(fileId, serializedAdditionalRawData); + return new ChatMessageTextContentItem(type, serializedAdditionalRawData, text); } - 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(CreateAssistantFileRequest)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ChatMessageTextContentItem)} does not support writing '{options.Format}' format."); } } - CreateAssistantFileRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ChatMessageTextContentItem 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 DeserializeCreateAssistantFileRequest(document.RootElement, options); + return DeserializeChatMessageTextContentItem(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(CreateAssistantFileRequest)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ChatMessageTextContentItem)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static CreateAssistantFileRequest FromResponse(Response response) + internal static new ChatMessageTextContentItem FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeCreateAssistantFileRequest(document.RootElement); + return DeserializeChatMessageTextContentItem(document.RootElement); } /// Convert into a . - internal virtual RequestContent ToRequestContent() + internal override RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.cs new file mode 100644 index 000000000000..46f0eb167d08 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A structured chat content item containing plain text. + public partial class ChatMessageTextContentItem : ChatMessageContentItem + { + /// Initializes a new instance of . + /// The content of the message. + /// is null. + public ChatMessageTextContentItem(string text) + { + Argument.AssertNotNull(text, nameof(text)); + + Type = "text"; + Text = text; + } + + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + /// The content of the message. + internal ChatMessageTextContentItem(string type, IDictionary serializedAdditionalRawData, string text) : base(type, serializedAdditionalRawData) + { + Text = text; + } + + /// Initializes a new instance of for deserialization. + internal ChatMessageTextContentItem() + { + } + + /// The content of the message. + public string Text { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.Serialization.cs new file mode 100644 index 000000000000..0521e4379402 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.Serialization.cs @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestAssistantMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatRequestAssistantMessage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Content != null) + { + writer.WritePropertyName("content"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Content); +#else + using (JsonDocument document = JsonDocument.Parse(Content)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("content"); + } + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (Optional.IsCollectionDefined(ToolCalls)) + { + writer.WritePropertyName("tool_calls"u8); + writer.WriteStartArray(); + foreach (var item in ToolCalls) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(FunctionCall)) + { + writer.WritePropertyName("function_call"u8); + writer.WriteObjectValue(FunctionCall, options); + } + if (Optional.IsDefined(Refusal)) + { + if (Refusal != null) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + } + else + { + writer.WriteNull("refusal"); + } + } + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatRequestAssistantMessage 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(ChatRequestAssistantMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestAssistantMessage(document.RootElement, options); + } + + internal static ChatRequestAssistantMessage DeserializeChatRequestAssistantMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BinaryData content = default; + string name = default; + IList toolCalls = default; + FunctionCall functionCall = default; + string refusal = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + content = null; + continue; + } + content = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatCompletionsToolCall.DeserializeChatCompletionsToolCall(item, options)); + } + toolCalls = array; + continue; + } + if (property.NameEquals("function_call"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + functionCall = FunctionCall.DeserializeFunctionCall(property.Value, options); + continue; + } + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + refusal = null; + continue; + } + refusal = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestAssistantMessage( + role, + serializedAdditionalRawData, + content, + name, + toolCalls ?? new ChangeTrackingList(), + functionCall, + refusal); + } + + 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(ChatRequestAssistantMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestAssistantMessage 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 DeserializeChatRequestAssistantMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestAssistantMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestAssistantMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatRequestAssistantMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.cs new file mode 100644 index 000000000000..581014adfeed --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A request chat message representing response or action from the assistant. + public partial class ChatRequestAssistantMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The content of the message. + public ChatRequestAssistantMessage(BinaryData content) + { + Role = ChatRole.Assistant; + Content = content; + ToolCalls = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// The content of the message. + /// An optional name for the participant. + /// + /// The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// + /// The function call that must be resolved and have its output appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// + /// The refusal message by the assistant. + internal ChatRequestAssistantMessage(ChatRole role, IDictionary serializedAdditionalRawData, BinaryData content, string name, IList toolCalls, FunctionCall functionCall, string refusal) : base(role, serializedAdditionalRawData) + { + Content = content; + Name = name; + ToolCalls = toolCalls; + FunctionCall = functionCall; + Refusal = refusal; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestAssistantMessage() + { + } + + /// + /// The content of the message. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// where T is of type + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Content { get; } + /// An optional name for the participant. + public string Name { get; set; } + /// + /// The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public IList ToolCalls { get; } + /// + /// The function call that must be resolved and have its output appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// + public FunctionCall FunctionCall { get; set; } + /// The refusal message by the assistant. + public string Refusal { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.Serialization.cs new file mode 100644 index 000000000000..21f009c89ce9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.Serialization.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestFunctionMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatRequestFunctionMessage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (Content != null) + { + writer.WritePropertyName("content"u8); + writer.WriteStringValue(Content); + } + else + { + writer.WriteNull("content"); + } + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatRequestFunctionMessage 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(ChatRequestFunctionMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestFunctionMessage(document.RootElement, options); + } + + internal static ChatRequestFunctionMessage DeserializeChatRequestFunctionMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string content = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + content = null; + continue; + } + content = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestFunctionMessage(role, serializedAdditionalRawData, name, content); + } + + 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(ChatRequestFunctionMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestFunctionMessage 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 DeserializeChatRequestFunctionMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestFunctionMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestFunctionMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatRequestFunctionMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.cs new file mode 100644 index 000000000000..a4588fc56d21 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A request chat message representing requested output from a configured function. + public partial class ChatRequestFunctionMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The name of the function that was called to produce output. + /// The output of the function as requested by the function call. + /// is null. + public ChatRequestFunctionMessage(string name, string content) + { + Argument.AssertNotNull(name, nameof(name)); + + Role = ChatRole.Function; + Name = name; + Content = content; + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// The name of the function that was called to produce output. + /// The output of the function as requested by the function call. + internal ChatRequestFunctionMessage(ChatRole role, IDictionary serializedAdditionalRawData, string name, string content) : base(role, serializedAdditionalRawData) + { + Name = name; + Content = content; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestFunctionMessage() + { + } + + /// The name of the function that was called to produce output. + public string Name { get; } + /// The output of the function as requested by the function call. + public string Content { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.Serialization.cs new file mode 100644 index 000000000000..e18a2792b837 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.Serialization.cs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatRequestMessage))] + public partial class ChatRequestMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatRequestMessage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatRequestMessage 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(ChatRequestMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestMessage(document.RootElement, options); + } + + internal static ChatRequestMessage DeserializeChatRequestMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("role", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "assistant": return ChatRequestAssistantMessage.DeserializeChatRequestAssistantMessage(element, options); + case "function": return ChatRequestFunctionMessage.DeserializeChatRequestFunctionMessage(element, options); + case "system": return ChatRequestSystemMessage.DeserializeChatRequestSystemMessage(element, options); + case "tool": return ChatRequestToolMessage.DeserializeChatRequestToolMessage(element, options); + case "user": return ChatRequestUserMessage.DeserializeChatRequestUserMessage(element, options); + } + } + return UnknownChatRequestMessage.DeserializeUnknownChatRequestMessage(element, 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(ChatRequestMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestMessage 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 DeserializeChatRequestMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatRequestMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatRequestMessage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.cs new file mode 100644 index 000000000000..31872565f53d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a chat message as provided in a request. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + public abstract partial class ChatRequestMessage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected ChatRequestMessage() + { + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + internal ChatRequestMessage(ChatRole role, IDictionary serializedAdditionalRawData) + { + Role = role; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The chat role associated with this message. + internal ChatRole Role { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.Serialization.cs new file mode 100644 index 000000000000..28b22e323f38 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.Serialization.cs @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestSystemMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatRequestSystemMessage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("content"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Content); +#else + using (JsonDocument document = JsonDocument.Parse(Content)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatRequestSystemMessage 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(ChatRequestSystemMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestSystemMessage(document.RootElement, options); + } + + internal static ChatRequestSystemMessage DeserializeChatRequestSystemMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BinaryData content = default; + string name = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + content = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestSystemMessage(role, serializedAdditionalRawData, content, name); + } + + 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(ChatRequestSystemMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestSystemMessage 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 DeserializeChatRequestSystemMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestSystemMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestSystemMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatRequestSystemMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.cs new file mode 100644 index 000000000000..388061a2d04a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A request chat message containing system instructions that influence how the model will generate a chat completions + /// response. + /// + public partial class ChatRequestSystemMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The contents of the system message. + /// is null. + public ChatRequestSystemMessage(BinaryData content) + { + Argument.AssertNotNull(content, nameof(content)); + + Role = ChatRole.System; + Content = content; + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// The contents of the system message. + /// An optional name for the participant. + internal ChatRequestSystemMessage(ChatRole role, IDictionary serializedAdditionalRawData, BinaryData content, string name) : base(role, serializedAdditionalRawData) + { + Content = content; + Name = name; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestSystemMessage() + { + } + + /// + /// The contents of the system message. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Content { get; } + /// An optional name for the participant. + public string Name { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.Serialization.cs new file mode 100644 index 000000000000..3811de06e84c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.Serialization.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestToolMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatRequestToolMessage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Content != null) + { + writer.WritePropertyName("content"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Content); +#else + using (JsonDocument document = JsonDocument.Parse(Content)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("content"); + } + writer.WritePropertyName("tool_call_id"u8); + writer.WriteStringValue(ToolCallId); + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatRequestToolMessage 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(ChatRequestToolMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestToolMessage(document.RootElement, options); + } + + internal static ChatRequestToolMessage DeserializeChatRequestToolMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BinaryData content = default; + string toolCallId = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + content = null; + continue; + } + content = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("tool_call_id"u8)) + { + toolCallId = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestToolMessage(role, serializedAdditionalRawData, content, toolCallId); + } + + 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(ChatRequestToolMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestToolMessage 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 DeserializeChatRequestToolMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestToolMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestToolMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatRequestToolMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.cs new file mode 100644 index 000000000000..62ea4297b93a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.cs @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A request chat message representing requested output from a configured tool. + public partial class ChatRequestToolMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The content of the message. + /// The ID of the tool call resolved by the provided content. + /// is null. + public ChatRequestToolMessage(BinaryData content, string toolCallId) + { + Argument.AssertNotNull(toolCallId, nameof(toolCallId)); + + Role = ChatRole.Tool; + Content = content; + ToolCallId = toolCallId; + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// The content of the message. + /// The ID of the tool call resolved by the provided content. + internal ChatRequestToolMessage(ChatRole role, IDictionary serializedAdditionalRawData, BinaryData content, string toolCallId) : base(role, serializedAdditionalRawData) + { + Content = content; + ToolCallId = toolCallId; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestToolMessage() + { + } + + /// + /// The content of the message. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Content { get; } + /// The ID of the tool call resolved by the provided content. + public string ToolCallId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.Serialization.cs new file mode 100644 index 000000000000..5604566bf589 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.Serialization.cs @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestUserMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatRequestUserMessage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("content"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Content); +#else + using (JsonDocument document = JsonDocument.Parse(Content)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatRequestUserMessage 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(ChatRequestUserMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestUserMessage(document.RootElement, options); + } + + internal static ChatRequestUserMessage DeserializeChatRequestUserMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BinaryData content = default; + string name = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + content = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestUserMessage(role, serializedAdditionalRawData, content, name); + } + + 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(ChatRequestUserMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestUserMessage 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 DeserializeChatRequestUserMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestUserMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestUserMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatRequestUserMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.cs new file mode 100644 index 000000000000..8f83ff4940d1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A request chat message representing user input to the assistant. + public partial class ChatRequestUserMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The contents of the user message, with available input types varying by selected model. + /// is null. + public ChatRequestUserMessage(BinaryData content) + { + Argument.AssertNotNull(content, nameof(content)); + + Role = ChatRole.User; + Content = content; + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// The contents of the user message, with available input types varying by selected model. + /// An optional name for the participant. + internal ChatRequestUserMessage(ChatRole role, IDictionary serializedAdditionalRawData, BinaryData content, string name) : base(role, serializedAdditionalRawData) + { + Content = content; + Name = name; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestUserMessage() + { + } + + /// + /// The contents of the user message, with available input types varying by selected model. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// where T is of type + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Content { get; } + /// An optional name for the participant. + public string Name { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.Serialization.cs new file mode 100644 index 000000000000..6295f99a759f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.Serialization.cs @@ -0,0 +1,237 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatResponseMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatResponseMessage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (Refusal != null) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + } + else + { + writer.WriteNull("refusal"); + } + if (Content != null) + { + writer.WritePropertyName("content"u8); + writer.WriteStringValue(Content); + } + else + { + writer.WriteNull("content"); + } + if (Optional.IsCollectionDefined(ToolCalls)) + { + writer.WritePropertyName("tool_calls"u8); + writer.WriteStartArray(); + foreach (var item in ToolCalls) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(FunctionCall)) + { + writer.WritePropertyName("function_call"u8); + writer.WriteObjectValue(FunctionCall, options); + } + if (Optional.IsDefined(AzureExtensionsContext)) + { + writer.WritePropertyName("context"u8); + writer.WriteObjectValue(AzureExtensionsContext, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatResponseMessage 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(ChatResponseMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatResponseMessage(document.RootElement, options); + } + + internal static ChatResponseMessage DeserializeChatResponseMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatRole role = default; + string refusal = default; + string content = default; + IReadOnlyList toolCalls = default; + FunctionCall functionCall = default; + AzureChatExtensionsMessageContext context = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + refusal = null; + continue; + } + refusal = property.Value.GetString(); + continue; + } + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + content = null; + continue; + } + content = property.Value.GetString(); + continue; + } + if (property.NameEquals("tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatCompletionsToolCall.DeserializeChatCompletionsToolCall(item, options)); + } + toolCalls = array; + continue; + } + if (property.NameEquals("function_call"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + functionCall = FunctionCall.DeserializeFunctionCall(property.Value, options); + continue; + } + if (property.NameEquals("context"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + context = AzureChatExtensionsMessageContext.DeserializeAzureChatExtensionsMessageContext(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatResponseMessage( + role, + refusal, + content, + toolCalls ?? new ChangeTrackingList(), + functionCall, + context, + serializedAdditionalRawData); + } + + 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(ChatResponseMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatResponseMessage 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 DeserializeChatResponseMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatResponseMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatResponseMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatResponseMessage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.cs new file mode 100644 index 000000000000..c62e3c7692a3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of a chat message as received in a response. + public partial class ChatResponseMessage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The chat role associated with the message. + /// The refusal message generated by the model. + /// The content of the message. + internal ChatResponseMessage(ChatRole role, string refusal, string content) + { + Role = role; + Refusal = refusal; + Content = content; + ToolCalls = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The chat role associated with the message. + /// The refusal message generated by the model. + /// The content of the message. + /// + /// The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// + /// The function call that must be resolved and have its output appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// + /// + /// If Azure OpenAI chat extensions are configured, this array represents the incremental steps performed by those + /// extensions while processing the chat completions request. + /// + /// Keeps track of any properties unknown to the library. + internal ChatResponseMessage(ChatRole role, string refusal, string content, IReadOnlyList toolCalls, FunctionCall functionCall, AzureChatExtensionsMessageContext azureExtensionsContext, IDictionary serializedAdditionalRawData) + { + Role = role; + Refusal = refusal; + Content = content; + ToolCalls = toolCalls; + FunctionCall = functionCall; + AzureExtensionsContext = azureExtensionsContext; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatResponseMessage() + { + } + + /// The chat role associated with the message. + public ChatRole Role { get; } + /// The refusal message generated by the model. + public string Refusal { get; } + /// The content of the message. + public string Content { get; } + /// + /// The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public IReadOnlyList ToolCalls { get; } + /// + /// The function call that must be resolved and have its output appended to subsequent input messages for the chat + /// completions request to resolve as configured. + /// + public FunctionCall FunctionCall { get; } + /// + /// If Azure OpenAI chat extensions are configured, this array represents the incremental steps performed by those + /// extensions while processing the chat completions request. + /// + public AzureChatExtensionsMessageContext AzureExtensionsContext { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRetrievedDocument.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRetrievedDocument.cs deleted file mode 100644 index 96e966ba79e0..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRetrievedDocument.cs +++ /dev/null @@ -1,109 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureChatMessageContextAllRetrievedDocuments. - public partial class ChatRetrievedDocument - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// The content of the citation. - /// The search queries executed to retrieve documents. - /// The index of the data source used for retrieval. - /// or is null. - internal ChatRetrievedDocument(string content, IEnumerable searchQueries, int dataSourceIndex) - { - Argument.AssertNotNull(content, nameof(content)); - Argument.AssertNotNull(searchQueries, nameof(searchQueries)); - - Content = content; - SearchQueries = searchQueries.ToList(); - DataSourceIndex = dataSourceIndex; - } - - /// Initializes a new instance of . - /// The content of the citation. - /// The title for the citation. - /// The URL of the citation. - /// The file path for the citation. - /// The chunk ID for the citation. - /// The rerank score for the retrieval. - /// The search queries executed to retrieve documents. - /// The index of the data source used for retrieval. - /// The original search score for the retrieval. - /// If applicable, an indication of why the document was filtered. - /// Keeps track of any properties unknown to the library. - internal ChatRetrievedDocument(string content, string title, Uri uri, string filePath, string chunkId, double? rerankScore, IReadOnlyList searchQueries, int dataSourceIndex, double? originalSearchScore, ChatDocumentFilterReason? filterReason, IDictionary serializedAdditionalRawData) - { - Content = content; - Title = title; - Uri = uri; - FilePath = filePath; - ChunkId = chunkId; - RerankScore = rerankScore; - SearchQueries = searchQueries; - DataSourceIndex = dataSourceIndex; - OriginalSearchScore = originalSearchScore; - FilterReason = filterReason; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal ChatRetrievedDocument() - { - } - - /// The content of the citation. - public string Content { get; } - /// The title for the citation. - public string Title { get; } - /// The chunk ID for the citation. - public string ChunkId { get; } - /// The rerank score for the retrieval. - public double? RerankScore { get; } - /// The search queries executed to retrieve documents. - public IReadOnlyList SearchQueries { get; } - /// The index of the data source used for retrieval. - public int DataSourceIndex { get; } - /// The original search score for the retrieval. - public double? OriginalSearchScore { get; } - /// If applicable, an indication of why the document was filtered. - public ChatDocumentFilterReason? FilterReason { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRole.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRole.cs new file mode 100644 index 000000000000..f169dc55ef81 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRole.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// A description of the intended purpose of a message within a chat completions interaction. + public readonly partial struct ChatRole : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ChatRole(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SystemValue = "system"; + private const string AssistantValue = "assistant"; + private const string UserValue = "user"; + private const string FunctionValue = "function"; + private const string ToolValue = "tool"; + + /// The role that instructs or sets the behavior of the assistant. + public static ChatRole System { get; } = new ChatRole(SystemValue); + /// The role that provides responses to system-instructed, user-prompted input. + public static ChatRole Assistant { get; } = new ChatRole(AssistantValue); + /// The role that provides input for chat completions. + public static ChatRole User { get; } = new ChatRole(UserValue); + /// The role that provides function results for chat completions. + public static ChatRole Function { get; } = new ChatRole(FunctionValue); + /// The role that represents extension tool activity within a chat completions operation. + public static ChatRole Tool { get; } = new ChatRole(ToolValue); + /// Determines if two values are the same. + public static bool operator ==(ChatRole left, ChatRole right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ChatRole left, ChatRole right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ChatRole(string value) => new ChatRole(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ChatRole other && Equals(other); + /// + public bool Equals(ChatRole other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.Serialization.cs new file mode 100644 index 000000000000..47317f79c4cd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.Serialization.cs @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatTokenLogProbabilityInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatTokenLogProbabilityInfo)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("token"u8); + writer.WriteStringValue(Token); + writer.WritePropertyName("logprob"u8); + writer.WriteNumberValue(LogProbability); + if (Utf8ByteValues != null && Optional.IsCollectionDefined(Utf8ByteValues)) + { + writer.WritePropertyName("bytes"u8); + writer.WriteStartArray(); + foreach (var item in Utf8ByteValues) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("bytes"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatTokenLogProbabilityInfo 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(ChatTokenLogProbabilityInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatTokenLogProbabilityInfo(document.RootElement, options); + } + + internal static ChatTokenLogProbabilityInfo DeserializeChatTokenLogProbabilityInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string token = default; + float logprob = default; + IReadOnlyList bytes = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("token"u8)) + { + token = property.Value.GetString(); + continue; + } + if (property.NameEquals("logprob"u8)) + { + logprob = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("bytes"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + bytes = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + bytes = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatTokenLogProbabilityInfo(token, logprob, bytes, serializedAdditionalRawData); + } + + 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(ChatTokenLogProbabilityInfo)} does not support writing '{options.Format}' format."); + } + } + + ChatTokenLogProbabilityInfo 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 DeserializeChatTokenLogProbabilityInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatTokenLogProbabilityInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatTokenLogProbabilityInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatTokenLogProbabilityInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.cs new file mode 100644 index 000000000000..7583c16e09ac --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// A representation of the log probability information for a single message content token. + public partial class ChatTokenLogProbabilityInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// is null. + internal ChatTokenLogProbabilityInfo(string token, float logProbability, IEnumerable utf8ByteValues) + { + Argument.AssertNotNull(token, nameof(token)); + + Token = token; + LogProbability = logProbability; + Utf8ByteValues = utf8ByteValues?.ToList(); + } + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// Keeps track of any properties unknown to the library. + internal ChatTokenLogProbabilityInfo(string token, float logProbability, IReadOnlyList utf8ByteValues, IDictionary serializedAdditionalRawData) + { + Token = token; + LogProbability = logProbability; + Utf8ByteValues = utf8ByteValues; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatTokenLogProbabilityInfo() + { + } + + /// The message content token. + public string Token { get; } + /// The log probability of the message content token. + public float LogProbability { get; } + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + public IReadOnlyList Utf8ByteValues { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.Serialization.cs new file mode 100644 index 000000000000..4c4fbfd323ea --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.Serialization.cs @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatTokenLogProbabilityResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatTokenLogProbabilityResult)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("token"u8); + writer.WriteStringValue(Token); + writer.WritePropertyName("logprob"u8); + writer.WriteNumberValue(LogProbability); + if (Utf8ByteValues != null && Optional.IsCollectionDefined(Utf8ByteValues)) + { + writer.WritePropertyName("bytes"u8); + writer.WriteStartArray(); + foreach (var item in Utf8ByteValues) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("bytes"); + } + if (TopLogProbabilityEntries != null && Optional.IsCollectionDefined(TopLogProbabilityEntries)) + { + writer.WritePropertyName("top_logprobs"u8); + writer.WriteStartArray(); + foreach (var item in TopLogProbabilityEntries) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("top_logprobs"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatTokenLogProbabilityResult 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(ChatTokenLogProbabilityResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatTokenLogProbabilityResult(document.RootElement, options); + } + + internal static ChatTokenLogProbabilityResult DeserializeChatTokenLogProbabilityResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string token = default; + float logprob = default; + IReadOnlyList bytes = default; + IReadOnlyList topLogprobs = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("token"u8)) + { + token = property.Value.GetString(); + continue; + } + if (property.NameEquals("logprob"u8)) + { + logprob = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("bytes"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + bytes = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + bytes = array; + continue; + } + if (property.NameEquals("top_logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topLogprobs = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatTokenLogProbabilityInfo.DeserializeChatTokenLogProbabilityInfo(item, options)); + } + topLogprobs = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatTokenLogProbabilityResult(token, logprob, bytes, topLogprobs, serializedAdditionalRawData); + } + + 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(ChatTokenLogProbabilityResult)} does not support writing '{options.Format}' format."); + } + } + + ChatTokenLogProbabilityResult 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 DeserializeChatTokenLogProbabilityResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatTokenLogProbabilityResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatTokenLogProbabilityResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChatTokenLogProbabilityResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.cs new file mode 100644 index 000000000000..d7fe8b840266 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// A representation of the log probability information for a single content token, including a list of most likely tokens if 'top_logprobs' were requested. + public partial class ChatTokenLogProbabilityResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// The list of most likely tokens and their log probability information, as requested via 'top_logprobs'. + /// is null. + internal ChatTokenLogProbabilityResult(string token, float logProbability, IEnumerable utf8ByteValues, IEnumerable topLogProbabilityEntries) + { + Argument.AssertNotNull(token, nameof(token)); + + Token = token; + LogProbability = logProbability; + Utf8ByteValues = utf8ByteValues?.ToList(); + TopLogProbabilityEntries = topLogProbabilityEntries?.ToList(); + } + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// The list of most likely tokens and their log probability information, as requested via 'top_logprobs'. + /// Keeps track of any properties unknown to the library. + internal ChatTokenLogProbabilityResult(string token, float logProbability, IReadOnlyList utf8ByteValues, IReadOnlyList topLogProbabilityEntries, IDictionary serializedAdditionalRawData) + { + Token = token; + LogProbability = logProbability; + Utf8ByteValues = utf8ByteValues; + TopLogProbabilityEntries = topLogProbabilityEntries; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatTokenLogProbabilityResult() + { + } + + /// The message content token. + public string Token { get; } + /// The log probability of the message content token. + public float LogProbability { get; } + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + public IReadOnlyList Utf8ByteValues { get; } + /// The list of most likely tokens and their log probability information, as requested via 'top_logprobs'. + public IReadOnlyList TopLogProbabilityEntries { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.Serialization.cs new file mode 100644 index 000000000000..26680759e1a1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.Serialization.cs @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class Choice : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(Choice)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + if (Optional.IsDefined(ContentFilterResults)) + { + writer.WritePropertyName("content_filter_results"u8); + writer.WriteObjectValue(ContentFilterResults, options); + } + if (LogProbabilityModel != null) + { + writer.WritePropertyName("logprobs"u8); + writer.WriteObjectValue(LogProbabilityModel, options); + } + else + { + writer.WriteNull("logprobs"); + } + if (FinishReason != null) + { + writer.WritePropertyName("finish_reason"u8); + writer.WriteStringValue(FinishReason.Value.ToString()); + } + else + { + writer.WriteNull("finish_reason"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + Choice 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(Choice)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChoice(document.RootElement, options); + } + + internal static Choice DeserializeChoice(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + int index = default; + ContentFilterResultsForChoice contentFilterResults = default; + CompletionsLogProbabilityModel logprobs = default; + CompletionsFinishReason? finishReason = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("content_filter_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + contentFilterResults = ContentFilterResultsForChoice.DeserializeContentFilterResultsForChoice(property.Value, options); + continue; + } + if (property.NameEquals("logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + logprobs = null; + continue; + } + logprobs = CompletionsLogProbabilityModel.DeserializeCompletionsLogProbabilityModel(property.Value, options); + continue; + } + if (property.NameEquals("finish_reason"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + finishReason = null; + continue; + } + finishReason = new CompletionsFinishReason(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Choice( + text, + index, + contentFilterResults, + logprobs, + finishReason, + serializedAdditionalRawData); + } + + 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(Choice)} does not support writing '{options.Format}' format."); + } + } + + Choice 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 DeserializeChoice(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Choice)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static Choice FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeChoice(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.cs new file mode 100644 index 000000000000..167dc6a38b70 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.cs @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// The representation of a single prompt completion as part of an overall completions request. + /// Generally, `n` choices are generated per provided prompt with a default value of 1. + /// Token limits and other settings may limit the number of choices generated. + /// + public partial class Choice + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The generated text for a given completions prompt. + /// The ordered index associated with this completions choice. + /// The log probabilities model for tokens associated with this completions choice. + /// Reason for finishing. + /// is null. + internal Choice(string text, int index, CompletionsLogProbabilityModel logProbabilityModel, CompletionsFinishReason? finishReason) + { + Argument.AssertNotNull(text, nameof(text)); + + Text = text; + Index = index; + LogProbabilityModel = logProbabilityModel; + FinishReason = finishReason; + } + + /// Initializes a new instance of . + /// The generated text for a given completions prompt. + /// The ordered index associated with this completions choice. + /// + /// Information about the content filtering category (hate, sexual, violence, self_harm), if it + /// has been detected, as well as the severity level (very_low, low, medium, high-scale that + /// determines the intensity and risk level of harmful content) and if it has been filtered or not. + /// + /// The log probabilities model for tokens associated with this completions choice. + /// Reason for finishing. + /// Keeps track of any properties unknown to the library. + internal Choice(string text, int index, ContentFilterResultsForChoice contentFilterResults, CompletionsLogProbabilityModel logProbabilityModel, CompletionsFinishReason? finishReason, IDictionary serializedAdditionalRawData) + { + Text = text; + Index = index; + ContentFilterResults = contentFilterResults; + LogProbabilityModel = logProbabilityModel; + FinishReason = finishReason; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Choice() + { + } + + /// The generated text for a given completions prompt. + public string Text { get; } + /// The ordered index associated with this completions choice. + public int Index { get; } + /// + /// Information about the content filtering category (hate, sexual, violence, self_harm), if it + /// has been detected, as well as the severity level (very_low, low, medium, high-scale that + /// determines the intensity and risk level of harmful content) and if it has been filtered or not. + /// + public ContentFilterResultsForChoice ContentFilterResults { get; } + /// The log probabilities model for tokens associated with this completions choice. + public CompletionsLogProbabilityModel LogProbabilityModel { get; } + /// Reason for finishing. + public CompletionsFinishReason? FinishReason { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.Serialization.cs new file mode 100644 index 000000000000..9a459ac6b9c7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.Serialization.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompleteUploadRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CompleteUploadRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("part_ids"u8); + writer.WriteStartArray(); + foreach (var item in PartIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(Md5)) + { + writer.WritePropertyName("md5"u8); + writer.WriteStringValue(Md5); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CompleteUploadRequest 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(CompleteUploadRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompleteUploadRequest(document.RootElement, options); + } + + internal static CompleteUploadRequest DeserializeCompleteUploadRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList partIds = default; + string md5 = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("part_ids"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + partIds = array; + continue; + } + if (property.NameEquals("md5"u8)) + { + md5 = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompleteUploadRequest(partIds, md5, serializedAdditionalRawData); + } + + 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(CompleteUploadRequest)} does not support writing '{options.Format}' format."); + } + } + + CompleteUploadRequest 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 DeserializeCompleteUploadRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompleteUploadRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompleteUploadRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCompleteUploadRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.cs new file mode 100644 index 000000000000..0022308524f9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The request body of an upload completion request. + public partial class CompleteUploadRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ordered list of Part IDs. + /// is null. + public CompleteUploadRequest(IEnumerable partIds) + { + Argument.AssertNotNull(partIds, nameof(partIds)); + + PartIds = partIds.ToList(); + } + + /// Initializes a new instance of . + /// The ordered list of Part IDs. + /// The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect. + /// Keeps track of any properties unknown to the library. + internal CompleteUploadRequest(IList partIds, string md5, IDictionary serializedAdditionalRawData) + { + PartIds = partIds; + Md5 = md5; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CompleteUploadRequest() + { + } + + /// The ordered list of Part IDs. + public IList PartIds { get; } + /// The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect. + public string Md5 { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.Serialization.cs new file mode 100644 index 000000000000..3e12e8602555 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.Serialization.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class Completions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(Completions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("created"u8); + writer.WriteNumberValue(Created, "U"); + if (Optional.IsCollectionDefined(PromptFilterResults)) + { + writer.WritePropertyName("prompt_filter_results"u8); + writer.WriteStartArray(); + foreach (var item in PromptFilterResults) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + writer.WritePropertyName("choices"u8); + writer.WriteStartArray(); + foreach (var item in Choices) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + if (Optional.IsDefined(SystemFingerprint)) + { + writer.WritePropertyName("system_fingerprint"u8); + writer.WriteStringValue(SystemFingerprint); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + Completions 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(Completions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletions(document.RootElement, options); + } + + internal static Completions DeserializeCompletions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset created = default; + IReadOnlyList promptFilterResults = default; + IReadOnlyList choices = default; + CompletionsUsage usage = default; + string systemFingerprint = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("created"u8)) + { + created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("prompt_filter_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ContentFilterResultsForPrompt.DeserializeContentFilterResultsForPrompt(item, options)); + } + promptFilterResults = array; + continue; + } + if (property.NameEquals("choices"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(Choice.DeserializeChoice(item, options)); + } + choices = array; + continue; + } + if (property.NameEquals("usage"u8)) + { + usage = CompletionsUsage.DeserializeCompletionsUsage(property.Value, options); + continue; + } + if (property.NameEquals("system_fingerprint"u8)) + { + systemFingerprint = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Completions( + id, + created, + promptFilterResults ?? new ChangeTrackingList(), + choices, + usage, + systemFingerprint, + serializedAdditionalRawData); + } + + 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(Completions)} does not support writing '{options.Format}' format."); + } + } + + Completions 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 DeserializeCompletions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Completions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static Completions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCompletions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.cs new file mode 100644 index 000000000000..005de8a20f34 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.cs @@ -0,0 +1,144 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// Representation of the response data from a completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + public partial class Completions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A unique identifier associated with this completions response. + /// + /// The first timestamp associated with generation activity for this completions response, + /// represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. + /// + /// + /// The collection of completions choices associated with this completions response. + /// Generally, `n` choices are generated per provided prompt with a default value of 1. + /// Token limits and other settings may limit the number of choices generated. + /// + /// Usage information for tokens processed and generated as part of this completions operation. + /// , or is null. + internal Completions(string id, DateTimeOffset created, IEnumerable choices, CompletionsUsage usage) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(choices, nameof(choices)); + Argument.AssertNotNull(usage, nameof(usage)); + + Id = id; + Created = created; + PromptFilterResults = new ChangeTrackingList(); + Choices = choices.ToList(); + Usage = usage; + } + + /// Initializes a new instance of . + /// A unique identifier associated with this completions response. + /// + /// The first timestamp associated with generation activity for this completions response, + /// represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. + /// + /// + /// Content filtering results for zero or more prompts in the request. In a streaming request, + /// results for different prompts may arrive at different times or in different orders. + /// + /// + /// The collection of completions choices associated with this completions response. + /// Generally, `n` choices are generated per provided prompt with a default value of 1. + /// Token limits and other settings may limit the number of choices generated. + /// + /// Usage information for tokens processed and generated as part of this completions operation. + /// + /// This fingerprint represents the backend configuration that the model runs with. + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + /// + /// Keeps track of any properties unknown to the library. + internal Completions(string id, DateTimeOffset created, IReadOnlyList promptFilterResults, IReadOnlyList choices, CompletionsUsage usage, string systemFingerprint, IDictionary serializedAdditionalRawData) + { + Id = id; + Created = created; + PromptFilterResults = promptFilterResults; + Choices = choices; + Usage = usage; + SystemFingerprint = systemFingerprint; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Completions() + { + } + + /// A unique identifier associated with this completions response. + public string Id { get; } + /// + /// The first timestamp associated with generation activity for this completions response, + /// represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. + /// + public DateTimeOffset Created { get; } + /// + /// Content filtering results for zero or more prompts in the request. In a streaming request, + /// results for different prompts may arrive at different times or in different orders. + /// + public IReadOnlyList PromptFilterResults { get; } + /// + /// The collection of completions choices associated with this completions response. + /// Generally, `n` choices are generated per provided prompt with a default value of 1. + /// Token limits and other settings may limit the number of choices generated. + /// + public IReadOnlyList Choices { get; } + /// Usage information for tokens processed and generated as part of this completions operation. + public CompletionsUsage Usage { get; } + /// + /// This fingerprint represents the backend configuration that the model runs with. + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + /// + public string SystemFingerprint { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsFinishReason.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsFinishReason.cs new file mode 100644 index 000000000000..4270844fe202 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsFinishReason.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Representation of the manner in which a completions response concluded. + public readonly partial struct CompletionsFinishReason : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public CompletionsFinishReason(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string StoppedValue = "stop"; + private const string TokenLimitReachedValue = "length"; + private const string ContentFilteredValue = "content_filter"; + private const string FunctionCallValue = "function_call"; + private const string ToolCallsValue = "tool_calls"; + + /// Completions ended normally and reached its end of token generation. + public static CompletionsFinishReason Stopped { get; } = new CompletionsFinishReason(StoppedValue); + /// Completions exhausted available token limits before generation could complete. + public static CompletionsFinishReason TokenLimitReached { get; } = new CompletionsFinishReason(TokenLimitReachedValue); + /// + /// Completions generated a response that was identified as potentially sensitive per content + /// moderation policies. + /// + public static CompletionsFinishReason ContentFiltered { get; } = new CompletionsFinishReason(ContentFilteredValue); + /// Completion ended normally, with the model requesting a function to be called. + public static CompletionsFinishReason FunctionCall { get; } = new CompletionsFinishReason(FunctionCallValue); + /// Completion ended with the model calling a provided tool for output. + public static CompletionsFinishReason ToolCalls { get; } = new CompletionsFinishReason(ToolCallsValue); + /// Determines if two values are the same. + public static bool operator ==(CompletionsFinishReason left, CompletionsFinishReason right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(CompletionsFinishReason left, CompletionsFinishReason right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator CompletionsFinishReason(string value) => new CompletionsFinishReason(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is CompletionsFinishReason other && Equals(other); + /// + public bool Equals(CompletionsFinishReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.Serialization.cs new file mode 100644 index 000000000000..85e4d0cd3152 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.Serialization.cs @@ -0,0 +1,246 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompletionsLogProbabilityModel : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CompletionsLogProbabilityModel)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("tokens"u8); + writer.WriteStartArray(); + foreach (var item in Tokens) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("token_logprobs"u8); + writer.WriteStartArray(); + foreach (var item in TokenLogProbabilities) + { + if (item == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteNumberValue(item.Value); + } + writer.WriteEndArray(); + writer.WritePropertyName("top_logprobs"u8); + writer.WriteStartArray(); + foreach (var item in TopLogProbabilities) + { + if (item == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteStartObject(); + foreach (var item0 in item) + { + writer.WritePropertyName(item0.Key); + if (item0.Value == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteNumberValue(item0.Value.Value); + } + writer.WriteEndObject(); + } + writer.WriteEndArray(); + writer.WritePropertyName("text_offset"u8); + writer.WriteStartArray(); + foreach (var item in TextOffsets) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CompletionsLogProbabilityModel 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(CompletionsLogProbabilityModel)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletionsLogProbabilityModel(document.RootElement, options); + } + + internal static CompletionsLogProbabilityModel DeserializeCompletionsLogProbabilityModel(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList tokens = default; + IReadOnlyList tokenLogprobs = default; + IReadOnlyList> topLogprobs = default; + IReadOnlyList textOffset = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("tokens"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + tokens = array; + continue; + } + if (property.NameEquals("token_logprobs"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetSingle()); + } + } + tokenLogprobs = array; + continue; + } + if (property.NameEquals("top_logprobs"u8)) + { + List> array = new List>(); + foreach (var item in property.Value.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + Dictionary dictionary = new Dictionary(); + foreach (var property0 in item.EnumerateObject()) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(property0.Name, null); + } + else + { + dictionary.Add(property0.Name, property0.Value.GetSingle()); + } + } + array.Add(dictionary); + } + } + topLogprobs = array; + continue; + } + if (property.NameEquals("text_offset"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + textOffset = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompletionsLogProbabilityModel(tokens, tokenLogprobs, topLogprobs, textOffset, serializedAdditionalRawData); + } + + 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(CompletionsLogProbabilityModel)} does not support writing '{options.Format}' format."); + } + } + + CompletionsLogProbabilityModel 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 DeserializeCompletionsLogProbabilityModel(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompletionsLogProbabilityModel)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompletionsLogProbabilityModel FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCompletionsLogProbabilityModel(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.cs new file mode 100644 index 000000000000..5b486eac6e8c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Representation of a log probabilities model for a completions generation. + public partial class CompletionsLogProbabilityModel + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The textual forms of tokens evaluated in this probability model. + /// A collection of log probability values for the tokens in this completions data. + /// A mapping of tokens to maximum log probability values in this completions data. + /// The text offsets associated with tokens in this completions data. + /// , , or is null. + internal CompletionsLogProbabilityModel(IEnumerable tokens, IEnumerable tokenLogProbabilities, IEnumerable> topLogProbabilities, IEnumerable textOffsets) + { + Argument.AssertNotNull(tokens, nameof(tokens)); + Argument.AssertNotNull(tokenLogProbabilities, nameof(tokenLogProbabilities)); + Argument.AssertNotNull(topLogProbabilities, nameof(topLogProbabilities)); + Argument.AssertNotNull(textOffsets, nameof(textOffsets)); + + Tokens = tokens.ToList(); + TokenLogProbabilities = tokenLogProbabilities.ToList(); + TopLogProbabilities = topLogProbabilities.ToList(); + TextOffsets = textOffsets.ToList(); + } + + /// Initializes a new instance of . + /// The textual forms of tokens evaluated in this probability model. + /// A collection of log probability values for the tokens in this completions data. + /// A mapping of tokens to maximum log probability values in this completions data. + /// The text offsets associated with tokens in this completions data. + /// Keeps track of any properties unknown to the library. + internal CompletionsLogProbabilityModel(IReadOnlyList tokens, IReadOnlyList tokenLogProbabilities, IReadOnlyList> topLogProbabilities, IReadOnlyList textOffsets, IDictionary serializedAdditionalRawData) + { + Tokens = tokens; + TokenLogProbabilities = tokenLogProbabilities; + TopLogProbabilities = topLogProbabilities; + TextOffsets = textOffsets; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CompletionsLogProbabilityModel() + { + } + + /// The textual forms of tokens evaluated in this probability model. + public IReadOnlyList Tokens { get; } + /// A collection of log probability values for the tokens in this completions data. + public IReadOnlyList TokenLogProbabilities { get; } + /// A mapping of tokens to maximum log probability values in this completions data. + public IReadOnlyList> TopLogProbabilities { get; } + /// The text offsets associated with tokens in this completions data. + public IReadOnlyList TextOffsets { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.Serialization.cs new file mode 100644 index 000000000000..652a24e11069 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.Serialization.cs @@ -0,0 +1,436 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompletionsOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CompletionsOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("prompt"u8); + writer.WriteStartArray(); + foreach (var item in Prompts) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(MaxTokens)) + { + writer.WritePropertyName("max_tokens"u8); + writer.WriteNumberValue(MaxTokens.Value); + } + if (Optional.IsDefined(Temperature)) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + if (Optional.IsDefined(NucleusSamplingFactor)) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(NucleusSamplingFactor.Value); + } + if (Optional.IsCollectionDefined(TokenSelectionBiases)) + { + writer.WritePropertyName("logit_bias"u8); + writer.WriteStartObject(); + foreach (var item in TokenSelectionBiases) + { + writer.WritePropertyName(item.Key); + writer.WriteNumberValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(User)) + { + writer.WritePropertyName("user"u8); + writer.WriteStringValue(User); + } + if (Optional.IsDefined(ChoicesPerPrompt)) + { + writer.WritePropertyName("n"u8); + writer.WriteNumberValue(ChoicesPerPrompt.Value); + } + if (Optional.IsDefined(LogProbabilityCount)) + { + writer.WritePropertyName("logprobs"u8); + writer.WriteNumberValue(LogProbabilityCount.Value); + } + if (Optional.IsDefined(Suffix)) + { + writer.WritePropertyName("suffix"u8); + writer.WriteStringValue(Suffix); + } + if (Optional.IsDefined(Echo)) + { + writer.WritePropertyName("echo"u8); + writer.WriteBooleanValue(Echo.Value); + } + if (Optional.IsCollectionDefined(StopSequences)) + { + writer.WritePropertyName("stop"u8); + writer.WriteStartArray(); + foreach (var item in StopSequences) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(PresencePenalty)) + { + writer.WritePropertyName("presence_penalty"u8); + writer.WriteNumberValue(PresencePenalty.Value); + } + if (Optional.IsDefined(FrequencyPenalty)) + { + writer.WritePropertyName("frequency_penalty"u8); + writer.WriteNumberValue(FrequencyPenalty.Value); + } + if (Optional.IsDefined(GenerationSampleCount)) + { + writer.WritePropertyName("best_of"u8); + writer.WriteNumberValue(GenerationSampleCount.Value); + } + if (Optional.IsDefined(InternalShouldStreamResponse)) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(InternalShouldStreamResponse.Value); + } + if (Optional.IsDefined(StreamOptions)) + { + if (StreamOptions != null) + { + writer.WritePropertyName("stream_options"u8); + writer.WriteObjectValue(StreamOptions, options); + } + else + { + writer.WriteNull("stream_options"); + } + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + if (Optional.IsDefined(Seed)) + { + writer.WritePropertyName("seed"u8); + writer.WriteNumberValue(Seed.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CompletionsOptions 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(CompletionsOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletionsOptions(document.RootElement, options); + } + + internal static CompletionsOptions DeserializeCompletionsOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList prompt = default; + int? maxTokens = default; + float? temperature = default; + float? topP = default; + IDictionary logitBias = default; + string user = default; + int? n = default; + int? logprobs = default; + string suffix = default; + bool? echo = default; + IList stop = default; + float? presencePenalty = default; + float? frequencyPenalty = default; + int? bestOf = default; + bool? stream = default; + ChatCompletionStreamOptions streamOptions = default; + string model = default; + int? seed = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("prompt"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + prompt = array; + continue; + } + if (property.NameEquals("max_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("logit_bias"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetInt32()); + } + logitBias = dictionary; + continue; + } + if (property.NameEquals("user"u8)) + { + user = property.Value.GetString(); + continue; + } + if (property.NameEquals("n"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + n = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + logprobs = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("suffix"u8)) + { + suffix = property.Value.GetString(); + continue; + } + if (property.NameEquals("echo"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + echo = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stop"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + stop = array; + continue; + } + if (property.NameEquals("presence_penalty"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + presencePenalty = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("frequency_penalty"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + frequencyPenalty = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("best_of"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + bestOf = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("stream"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stream = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stream_options"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + streamOptions = null; + continue; + } + streamOptions = ChatCompletionStreamOptions.DeserializeChatCompletionStreamOptions(property.Value, options); + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (property.NameEquals("seed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + seed = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompletionsOptions( + prompt, + maxTokens, + temperature, + topP, + logitBias ?? new ChangeTrackingDictionary(), + user, + n, + logprobs, + suffix, + echo, + stop ?? new ChangeTrackingList(), + presencePenalty, + frequencyPenalty, + bestOf, + stream, + streamOptions, + model, + seed, + serializedAdditionalRawData); + } + + 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(CompletionsOptions)} does not support writing '{options.Format}' format."); + } + } + + CompletionsOptions 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 DeserializeCompletionsOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompletionsOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompletionsOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCompletionsOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.cs new file mode 100644 index 000000000000..0e88c5d42c95 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.cs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// The configuration information for a completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + public partial class CompletionsOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The prompts to generate completions from. + /// is null. + public CompletionsOptions(IEnumerable prompts) + { + Argument.AssertNotNull(prompts, nameof(prompts)); + + Prompts = prompts.ToList(); + TokenSelectionBiases = new ChangeTrackingDictionary(); + StopSequences = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The prompts to generate completions from. + /// The maximum number of tokens to generate. + /// + /// The sampling temperature to use that controls the apparent creativity of generated completions. + /// Higher values will make output more random while lower values will make results more focused + /// and deterministic. + /// It is not recommended to modify temperature and top_p for the same completions request as the + /// interaction of these two settings is difficult to predict. + /// + /// + /// An alternative to sampling with temperature called nucleus sampling. This value causes the + /// model to consider the results of tokens with the provided probability mass. As an example, a + /// value of 0.15 will cause only the tokens comprising the top 15% of probability mass to be + /// considered. + /// It is not recommended to modify temperature and top_p for the same completions request as the + /// interaction of these two settings is difficult to predict. + /// + /// + /// A map between GPT token IDs and bias scores that influences the probability of specific tokens + /// appearing in a completions response. Token IDs are computed via external tokenizer tools, while + /// bias scores reside in the range of -100 to 100 with minimum and maximum values corresponding to + /// a full ban or exclusive selection of a token, respectively. The exact behavior of a given bias + /// score varies by model. + /// + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + /// + /// The number of completions choices that should be generated per provided prompt as part of an + /// overall completions response. + /// Because this setting can generate many completions, it may quickly consume your token quota. + /// Use carefully and ensure reasonable settings for max_tokens and stop. + /// + /// + /// A value that controls the emission of log probabilities for the provided number of most likely + /// tokens within a completions response. + /// + /// The suffix that comes after a completion of inserted text. + /// + /// A value specifying whether completions responses should include input prompts as prefixes to + /// their generated output. + /// + /// A collection of textual sequences that will end completions generation. + /// + /// A value that influences the probability of generated tokens appearing based on their existing + /// presence in generated text. + /// Positive values will make tokens less likely to appear when they already exist and increase the + /// model's likelihood to output new topics. + /// + /// + /// A value that influences the probability of generated tokens appearing based on their cumulative + /// frequency in generated text. + /// Positive values will make tokens less likely to appear as their frequency increases and + /// decrease the likelihood of the model repeating the same statements verbatim. + /// + /// + /// A value that controls how many completions will be internally generated prior to response + /// formulation. + /// When used together with n, best_of controls the number of candidate completions and must be + /// greater than n. + /// Because this setting can generate many completions, it may quickly consume your token quota. + /// Use carefully and ensure reasonable settings for max_tokens and stop. + /// + /// A value indicating whether chat completions should be streamed for this request. + /// Options for streaming response. Only set this when you set `stream: true`. + /// + /// The model name to provide as part of this completions request. + /// Not applicable to Azure OpenAI, where deployment information should be included in the Azure + /// resource URI that's connected to. + /// + /// + /// If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + /// + /// Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + /// + /// Keeps track of any properties unknown to the library. + internal CompletionsOptions(IList prompts, int? maxTokens, float? temperature, float? nucleusSamplingFactor, IDictionary tokenSelectionBiases, string user, int? choicesPerPrompt, int? logProbabilityCount, string suffix, bool? echo, IList stopSequences, float? presencePenalty, float? frequencyPenalty, int? generationSampleCount, bool? internalShouldStreamResponse, ChatCompletionStreamOptions streamOptions, string deploymentName, int? seed, IDictionary serializedAdditionalRawData) + { + Prompts = prompts; + MaxTokens = maxTokens; + Temperature = temperature; + NucleusSamplingFactor = nucleusSamplingFactor; + TokenSelectionBiases = tokenSelectionBiases; + User = user; + ChoicesPerPrompt = choicesPerPrompt; + LogProbabilityCount = logProbabilityCount; + Suffix = suffix; + Echo = echo; + StopSequences = stopSequences; + PresencePenalty = presencePenalty; + FrequencyPenalty = frequencyPenalty; + GenerationSampleCount = generationSampleCount; + InternalShouldStreamResponse = internalShouldStreamResponse; + StreamOptions = streamOptions; + DeploymentName = deploymentName; + Seed = seed; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CompletionsOptions() + { + } + + /// The prompts to generate completions from. + public IList Prompts { get; } + /// The maximum number of tokens to generate. + public int? MaxTokens { get; set; } + /// + /// The sampling temperature to use that controls the apparent creativity of generated completions. + /// Higher values will make output more random while lower values will make results more focused + /// and deterministic. + /// It is not recommended to modify temperature and top_p for the same completions request as the + /// interaction of these two settings is difficult to predict. + /// + public float? Temperature { get; set; } + /// + /// An alternative to sampling with temperature called nucleus sampling. This value causes the + /// model to consider the results of tokens with the provided probability mass. As an example, a + /// value of 0.15 will cause only the tokens comprising the top 15% of probability mass to be + /// considered. + /// It is not recommended to modify temperature and top_p for the same completions request as the + /// interaction of these two settings is difficult to predict. + /// + public float? NucleusSamplingFactor { get; set; } + /// + /// A map between GPT token IDs and bias scores that influences the probability of specific tokens + /// appearing in a completions response. Token IDs are computed via external tokenizer tools, while + /// bias scores reside in the range of -100 to 100 with minimum and maximum values corresponding to + /// a full ban or exclusive selection of a token, respectively. The exact behavior of a given bias + /// score varies by model. + /// + public IDictionary TokenSelectionBiases { get; } + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + public string User { get; set; } + /// + /// The number of completions choices that should be generated per provided prompt as part of an + /// overall completions response. + /// Because this setting can generate many completions, it may quickly consume your token quota. + /// Use carefully and ensure reasonable settings for max_tokens and stop. + /// + public int? ChoicesPerPrompt { get; set; } + /// + /// A value that controls the emission of log probabilities for the provided number of most likely + /// tokens within a completions response. + /// + public int? LogProbabilityCount { get; set; } + /// The suffix that comes after a completion of inserted text. + public string Suffix { get; set; } + /// + /// A value specifying whether completions responses should include input prompts as prefixes to + /// their generated output. + /// + public bool? Echo { get; set; } + /// A collection of textual sequences that will end completions generation. + public IList StopSequences { get; } + /// + /// A value that influences the probability of generated tokens appearing based on their existing + /// presence in generated text. + /// Positive values will make tokens less likely to appear when they already exist and increase the + /// model's likelihood to output new topics. + /// + public float? PresencePenalty { get; set; } + /// + /// A value that influences the probability of generated tokens appearing based on their cumulative + /// frequency in generated text. + /// Positive values will make tokens less likely to appear as their frequency increases and + /// decrease the likelihood of the model repeating the same statements verbatim. + /// + public float? FrequencyPenalty { get; set; } + /// + /// A value that controls how many completions will be internally generated prior to response + /// formulation. + /// When used together with n, best_of controls the number of candidate completions and must be + /// greater than n. + /// Because this setting can generate many completions, it may quickly consume your token quota. + /// Use carefully and ensure reasonable settings for max_tokens and stop. + /// + public int? GenerationSampleCount { get; set; } + /// A value indicating whether chat completions should be streamed for this request. + public bool? InternalShouldStreamResponse { get; set; } + /// Options for streaming response. Only set this when you set `stream: true`. + public ChatCompletionStreamOptions StreamOptions { get; set; } + /// + /// The model name to provide as part of this completions request. + /// Not applicable to Azure OpenAI, where deployment information should be included in the Azure + /// resource URI that's connected to. + /// + public string DeploymentName { get; set; } + /// + /// If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result. + /// + /// Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + /// + public int? Seed { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.Serialization.cs new file mode 100644 index 000000000000..02e18395a92d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.Serialization.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompletionsUsage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CompletionsUsage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("completion_tokens"u8); + writer.WriteNumberValue(CompletionTokens); + writer.WritePropertyName("prompt_tokens"u8); + writer.WriteNumberValue(PromptTokens); + writer.WritePropertyName("total_tokens"u8); + writer.WriteNumberValue(TotalTokens); + if (Optional.IsDefined(CompletionTokensDetails)) + { + writer.WritePropertyName("completion_tokens_details"u8); + writer.WriteObjectValue(CompletionTokensDetails, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CompletionsUsage 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(CompletionsUsage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletionsUsage(document.RootElement, options); + } + + internal static CompletionsUsage DeserializeCompletionsUsage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int completionTokens = default; + int promptTokens = default; + int totalTokens = default; + CompletionsUsageCompletionTokensDetails completionTokensDetails = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("completion_tokens"u8)) + { + completionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("prompt_tokens"u8)) + { + promptTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("total_tokens"u8)) + { + totalTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("completion_tokens_details"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + completionTokensDetails = CompletionsUsageCompletionTokensDetails.DeserializeCompletionsUsageCompletionTokensDetails(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompletionsUsage(completionTokens, promptTokens, totalTokens, completionTokensDetails, serializedAdditionalRawData); + } + + 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(CompletionsUsage)} does not support writing '{options.Format}' format."); + } + } + + CompletionsUsage 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 DeserializeCompletionsUsage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompletionsUsage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompletionsUsage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCompletionsUsage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.cs new file mode 100644 index 000000000000..8f0490056805 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// Representation of the token counts processed for a completions request. + /// Counts consider all tokens across prompts, choices, choice alternates, best_of generations, and + /// other consumers. + /// + public partial class CompletionsUsage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The number of tokens generated across all completions emissions. + /// The number of tokens in the provided prompts for the completions request. + /// The total number of tokens processed for the completions request and response. + internal CompletionsUsage(int completionTokens, int promptTokens, int totalTokens) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + } + + /// Initializes a new instance of . + /// The number of tokens generated across all completions emissions. + /// The number of tokens in the provided prompts for the completions request. + /// The total number of tokens processed for the completions request and response. + /// Breakdown of tokens used in a completion. + /// Keeps track of any properties unknown to the library. + internal CompletionsUsage(int completionTokens, int promptTokens, int totalTokens, CompletionsUsageCompletionTokensDetails completionTokensDetails, IDictionary serializedAdditionalRawData) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + CompletionTokensDetails = completionTokensDetails; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CompletionsUsage() + { + } + + /// The number of tokens generated across all completions emissions. + public int CompletionTokens { get; } + /// The number of tokens in the provided prompts for the completions request. + public int PromptTokens { get; } + /// The total number of tokens processed for the completions request and response. + public int TotalTokens { get; } + /// Breakdown of tokens used in a completion. + public CompletionsUsageCompletionTokensDetails CompletionTokensDetails { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.Serialization.cs new file mode 100644 index 000000000000..28718cfdd940 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompletionsUsageCompletionTokensDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CompletionsUsageCompletionTokensDetails)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(ReasoningTokens)) + { + writer.WritePropertyName("reasoning_tokens"u8); + writer.WriteNumberValue(ReasoningTokens.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CompletionsUsageCompletionTokensDetails 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(CompletionsUsageCompletionTokensDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletionsUsageCompletionTokensDetails(document.RootElement, options); + } + + internal static CompletionsUsageCompletionTokensDetails DeserializeCompletionsUsageCompletionTokensDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? reasoningTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("reasoning_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + reasoningTokens = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompletionsUsageCompletionTokensDetails(reasoningTokens, serializedAdditionalRawData); + } + + 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(CompletionsUsageCompletionTokensDetails)} does not support writing '{options.Format}' format."); + } + } + + CompletionsUsageCompletionTokensDetails 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 DeserializeCompletionsUsageCompletionTokensDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompletionsUsageCompletionTokensDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompletionsUsageCompletionTokensDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCompletionsUsageCompletionTokensDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialCitationResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.cs similarity index 62% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialCitationResult.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.cs index 155740c21393..e2cf5d8994d8 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialCitationResult.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -7,8 +10,8 @@ namespace Azure.AI.OpenAI { - /// The AzureContentFilterResultForChoiceProtectedMaterialCodeCitation. - public partial class ContentFilterProtectedMaterialCitationResult + /// The CompletionsUsageCompletionTokensDetails. + public partial class CompletionsUsageCompletionTokensDetails { /// /// Keeps track of any properties unknown to the library. @@ -40,24 +43,23 @@ public partial class ContentFilterProtectedMaterialCitationResult /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal ContentFilterProtectedMaterialCitationResult() + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal CompletionsUsageCompletionTokensDetails() { } - /// Initializes a new instance of . - /// The name or identifier of the license associated with the detection. - /// The URL associated with the license. + /// Initializes a new instance of . + /// Tokens generated by the model for reasoning. /// Keeps track of any properties unknown to the library. - internal ContentFilterProtectedMaterialCitationResult(string license, Uri uri, IDictionary serializedAdditionalRawData) + internal CompletionsUsageCompletionTokensDetails(int? reasoningTokens, IDictionary serializedAdditionalRawData) { - License = license; - Uri = uri; - SerializedAdditionalRawData = serializedAdditionalRawData; + ReasoningTokens = reasoningTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// The name or identifier of the license associated with the detection. - public string License { get; } + /// Tokens generated by the model for reasoning. + public int? ReasoningTokens { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.Serialization.cs new file mode 100644 index 000000000000..65a5bb117995 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterBlocklistIdResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ContentFilterBlocklistIdResult)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ContentFilterBlocklistIdResult 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(ContentFilterBlocklistIdResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterBlocklistIdResult(document.RootElement, options); + } + + internal static ContentFilterBlocklistIdResult DeserializeContentFilterBlocklistIdResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool filtered = default; + string id = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filtered"u8)) + { + filtered = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterBlocklistIdResult(filtered, id, serializedAdditionalRawData); + } + + 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(ContentFilterBlocklistIdResult)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterBlocklistIdResult 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 DeserializeContentFilterBlocklistIdResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterBlocklistIdResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterBlocklistIdResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeContentFilterBlocklistIdResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistResultDetail.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.cs similarity index 59% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistResultDetail.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.cs index d0726035c32b..012d845ccce3 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistResultDetail.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -7,8 +10,8 @@ namespace Azure.AI.OpenAI { - /// The AzureContentFilterBlocklistResultDetail. - internal partial class InternalAzureContentFilterBlocklistResultDetail + /// Represents the outcome of an evaluation against a custom blocklist as performed by content filtering. + public partial class ContentFilterBlocklistIdResult { /// /// Keeps track of any properties unknown to the library. @@ -40,12 +43,13 @@ internal partial class InternalAzureContentFilterBlocklistResultDetail /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// A value indicating whether the blocklist produced a filtering action. + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. /// The ID of the custom blocklist evaluated. /// is null. - internal InternalAzureContentFilterBlocklistResultDetail(bool filtered, string id) + internal ContentFilterBlocklistIdResult(bool filtered, string id) { Argument.AssertNotNull(id, nameof(id)); @@ -53,26 +57,25 @@ internal InternalAzureContentFilterBlocklistResultDetail(bool filtered, string i Id = id; } - /// Initializes a new instance of . - /// A value indicating whether the blocklist produced a filtering action. + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. /// The ID of the custom blocklist evaluated. /// Keeps track of any properties unknown to the library. - internal InternalAzureContentFilterBlocklistResultDetail(bool filtered, string id, IDictionary serializedAdditionalRawData) + internal ContentFilterBlocklistIdResult(bool filtered, string id, IDictionary serializedAdditionalRawData) { Filtered = filtered; Id = id; - SerializedAdditionalRawData = serializedAdditionalRawData; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal InternalAzureContentFilterBlocklistResultDetail() + /// Initializes a new instance of for deserialization. + internal ContentFilterBlocklistIdResult() { } - /// A value indicating whether the blocklist produced a filtering action. - internal bool Filtered { get; set; } + /// A value indicating whether or not the content has been filtered. + public bool Filtered { get; } /// The ID of the custom blocklist evaluated. - internal string Id { get; set; } + public string Id { get; } } } - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.Serialization.cs new file mode 100644 index 000000000000..dc9381ee06b9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.Serialization.cs @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterCitedDetectionResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ContentFilterCitedDetectionResult)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + writer.WritePropertyName("detected"u8); + writer.WriteBooleanValue(Detected); + if (Optional.IsDefined(Url)) + { + writer.WritePropertyName("URL"u8); + writer.WriteStringValue(Url.AbsoluteUri); + } + if (Optional.IsDefined(License)) + { + writer.WritePropertyName("license"u8); + writer.WriteStringValue(License); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ContentFilterCitedDetectionResult 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(ContentFilterCitedDetectionResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterCitedDetectionResult(document.RootElement, options); + } + + internal static ContentFilterCitedDetectionResult DeserializeContentFilterCitedDetectionResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool filtered = default; + bool detected = default; + Uri url = default; + string license = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filtered"u8)) + { + filtered = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("detected"u8)) + { + detected = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("URL"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + url = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("license"u8)) + { + license = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterCitedDetectionResult(filtered, detected, url, license, serializedAdditionalRawData); + } + + 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(ContentFilterCitedDetectionResult)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterCitedDetectionResult 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 DeserializeContentFilterCitedDetectionResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterCitedDetectionResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterCitedDetectionResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeContentFilterCitedDetectionResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.cs new file mode 100644 index 000000000000..5e73e0beb4b2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Represents the outcome of a detection operation against protected resources as performed by content filtering. + public partial class ContentFilterCitedDetectionResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + internal ContentFilterCitedDetectionResult(bool filtered, bool detected) + { + Filtered = filtered; + Detected = detected; + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + /// The internet location associated with the detection. + /// The license description associated with the detection. + /// Keeps track of any properties unknown to the library. + internal ContentFilterCitedDetectionResult(bool filtered, bool detected, Uri url, string license, IDictionary serializedAdditionalRawData) + { + Filtered = filtered; + Detected = detected; + Url = url; + License = license; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ContentFilterCitedDetectionResult() + { + } + + /// A value indicating whether or not the content has been filtered. + public bool Filtered { get; } + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + public bool Detected { get; } + /// The internet location associated with the detection. + public Uri Url { get; } + /// The license description associated with the detection. + public string License { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.Serialization.cs similarity index 54% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistResult.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.Serialization.cs index a2f4dd0e63c4..3b06a2040887 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistResult.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.Serialization.cs @@ -1,49 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.AI.OpenAI { - public partial class ContentFilterBlocklistResult : IJsonModel + public partial class ContentFilterDetailedResults : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ContentFilterBlocklistResult)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ContentFilterDetailedResults)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (SerializedAdditionalRawData?.ContainsKey("details") != true && Optional.IsCollectionDefined(InternalDetails)) + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + if (Optional.IsCollectionDefined(Details)) { writer.WritePropertyName("details"u8); writer.WriteStartArray(); - foreach (var item in InternalDetails) + foreach (var item in Details) { - writer.WriteObjectValue(item, options); + writer.WriteObjectValue(item, options); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData != null) + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -58,19 +56,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model writer.WriteEndObject(); } - ContentFilterBlocklistResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ContentFilterDetailedResults 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(ContentFilterBlocklistResult)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ContentFilterDetailedResults)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterBlocklistResult(document.RootElement, options); + return DeserializeContentFilterDetailedResults(document.RootElement, options); } - internal static ContentFilterBlocklistResult DeserializeContentFilterBlocklistResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static ContentFilterDetailedResults DeserializeContentFilterDetailedResults(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -79,7 +77,7 @@ internal static ContentFilterBlocklistResult DeserializeContentFilterBlocklistRe return null; } bool filtered = default; - IReadOnlyList details = default; + IReadOnlyList details = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -95,67 +93,68 @@ internal static ContentFilterBlocklistResult DeserializeContentFilterBlocklistRe { continue; } - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(InternalAzureContentFilterBlocklistResultDetail.DeserializeInternalAzureContentFilterBlocklistResultDetail(item, options)); + array.Add(ContentFilterBlocklistIdResult.DeserializeContentFilterBlocklistIdResult(item, options)); } details = array; continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new ContentFilterBlocklistResult(filtered, details ?? new ChangeTrackingList(), serializedAdditionalRawData); + return new ContentFilterDetailedResults(filtered, details ?? new ChangeTrackingList(), 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(ContentFilterBlocklistResult)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ContentFilterDetailedResults)} does not support writing '{options.Format}' format."); } } - ContentFilterBlocklistResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ContentFilterDetailedResults 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 DeserializeContentFilterBlocklistResult(document.RootElement, options); + return DeserializeContentFilterDetailedResults(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ContentFilterBlocklistResult)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ContentFilterDetailedResults)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ContentFilterBlocklistResult FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static ContentFilterDetailedResults FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterBlocklistResult(document.RootElement); + return DeserializeContentFilterDetailedResults(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.cs similarity index 55% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistResult.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.cs index d033e0e34b57..c044a5f4eadf 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistResult.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -7,8 +10,8 @@ namespace Azure.AI.OpenAI { - /// A collection of true/false filtering results for configured custom blocklists. - public partial class ContentFilterBlocklistResult + /// Represents a structured collection of result details for content filtering. + public partial class ContentFilterDetailedResults { /// /// Keeps track of any properties unknown to the library. @@ -40,32 +43,35 @@ public partial class ContentFilterBlocklistResult /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// A value indicating whether any of the detailed blocklists resulted in a filtering action. - internal ContentFilterBlocklistResult(bool filtered) + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + internal ContentFilterDetailedResults(bool filtered) { Filtered = filtered; - InternalDetails = new ChangeTrackingList(); + Details = new ChangeTrackingList(); } - /// Initializes a new instance of . - /// A value indicating whether any of the detailed blocklists resulted in a filtering action. - /// The pairs of individual blocklist IDs and whether they resulted in a filtering action. + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// The collection of detailed blocklist result information. /// Keeps track of any properties unknown to the library. - internal ContentFilterBlocklistResult(bool filtered, IReadOnlyList internalDetails, IDictionary serializedAdditionalRawData) + internal ContentFilterDetailedResults(bool filtered, IReadOnlyList details, IDictionary serializedAdditionalRawData) { Filtered = filtered; - InternalDetails = internalDetails; - SerializedAdditionalRawData = serializedAdditionalRawData; + Details = details; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal ContentFilterBlocklistResult() + /// Initializes a new instance of for deserialization. + internal ContentFilterDetailedResults() { } - /// A value indicating whether any of the detailed blocklists resulted in a filtering action. + /// A value indicating whether or not the content has been filtered. public bool Filtered { get; } + /// The collection of detailed blocklist result information. + public IReadOnlyList Details { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.Serialization.cs index 9c520fede22f..7e922f14a0d0 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.Serialization.cs @@ -1,17 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.AI.OpenAI { - public partial class ContentFilterDetectionResult : IJsonModel + public partial class ContentFilterDetectionResult : IUtf8JsonSerializable, IJsonModel { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; @@ -21,24 +26,14 @@ void IJsonModel.Write(Utf8JsonWriter writer, Model } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (SerializedAdditionalRawData?.ContainsKey("detected") != true) + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + writer.WritePropertyName("detected"u8); + writer.WriteBooleanValue(Detected); + if (options.Format != "W" && _serializedAdditionalRawData != null) { - writer.WritePropertyName("detected"u8); - writer.WriteBooleanValue(Detected); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -91,7 +86,6 @@ internal static ContentFilterDetectionResult DeserializeContentFilterDetectionRe } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } @@ -131,17 +125,19 @@ ContentFilterDetectionResult IPersistableModel.Cre string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ContentFilterDetectionResult FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static ContentFilterDetectionResult FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); return DeserializeContentFilterDetectionResult(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.cs index 34aab24008fd..eed9a9faac26 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -7,10 +10,7 @@ namespace Azure.AI.OpenAI { - /// - /// A labeled content filter result item that indicates whether the content was detected and whether the content was - /// filtered. - /// + /// Represents the outcome of a detection operation performed by content filtering. public partial class ContentFilterDetectionResult { /// @@ -43,10 +43,11 @@ public partial class ContentFilterDetectionResult /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } + private IDictionary _serializedAdditionalRawData; + /// Initializes a new instance of . - /// Whether the content detection resulted in a content filtering action. - /// Whether the labeled content category was detected in the content. + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. internal ContentFilterDetectionResult(bool filtered, bool detected) { Filtered = filtered; @@ -54,14 +55,14 @@ internal ContentFilterDetectionResult(bool filtered, bool detected) } /// Initializes a new instance of . - /// Whether the content detection resulted in a content filtering action. - /// Whether the labeled content category was detected in the content. + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. /// Keeps track of any properties unknown to the library. internal ContentFilterDetectionResult(bool filtered, bool detected, IDictionary serializedAdditionalRawData) { Filtered = filtered; Detected = detected; - SerializedAdditionalRawData = serializedAdditionalRawData; + _serializedAdditionalRawData = serializedAdditionalRawData; } /// Initializes a new instance of for deserialization. @@ -69,9 +70,9 @@ internal ContentFilterDetectionResult() { } - /// Whether the content detection resulted in a content filtering action. + /// A value indicating whether or not the content has been filtered. public bool Filtered { get; } - /// Whether the labeled content category was detected in the content. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. public bool Detected { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialCitationResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialCitationResult.Serialization.cs deleted file mode 100644 index 6847bd6a8e6b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialCitationResult.Serialization.cs +++ /dev/null @@ -1,151 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - public partial class ContentFilterProtectedMaterialCitationResult : 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(ContentFilterProtectedMaterialCitationResult)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("license") != true && Optional.IsDefined(License)) - { - writer.WritePropertyName("license"u8); - writer.WriteStringValue(License); - } - if (SerializedAdditionalRawData?.ContainsKey("URL") != true && Optional.IsDefined(Uri)) - { - writer.WritePropertyName("URL"u8); - writer.WriteStringValue(Uri.AbsoluteUri); - } - 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(); - } - - ContentFilterProtectedMaterialCitationResult 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(ContentFilterProtectedMaterialCitationResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterProtectedMaterialCitationResult(document.RootElement, options); - } - - internal static ContentFilterProtectedMaterialCitationResult DeserializeContentFilterProtectedMaterialCitationResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string license = default; - Uri url = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("license"u8)) - { - license = property.Value.GetString(); - continue; - } - if (property.NameEquals("URL"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - url = new Uri(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ContentFilterProtectedMaterialCitationResult(license, url, serializedAdditionalRawData); - } - - 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(ContentFilterProtectedMaterialCitationResult)} does not support writing '{options.Format}' format."); - } - } - - ContentFilterProtectedMaterialCitationResult 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 DeserializeContentFilterProtectedMaterialCitationResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ContentFilterProtectedMaterialCitationResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ContentFilterProtectedMaterialCitationResult FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterProtectedMaterialCitationResult(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialResult.Serialization.cs deleted file mode 100644 index 96ed6972ea3c..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialResult.Serialization.cs +++ /dev/null @@ -1,162 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - public partial class ContentFilterProtectedMaterialResult : 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(ContentFilterProtectedMaterialResult)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (SerializedAdditionalRawData?.ContainsKey("detected") != true) - { - writer.WritePropertyName("detected"u8); - writer.WriteBooleanValue(Detected); - } - if (SerializedAdditionalRawData?.ContainsKey("citation") != true && Optional.IsDefined(Citation)) - { - writer.WritePropertyName("citation"u8); - writer.WriteObjectValue(Citation, 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(); - } - - ContentFilterProtectedMaterialResult 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(ContentFilterProtectedMaterialResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterProtectedMaterialResult(document.RootElement, options); - } - - internal static ContentFilterProtectedMaterialResult DeserializeContentFilterProtectedMaterialResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool filtered = default; - bool detected = default; - ContentFilterProtectedMaterialCitationResult citation = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("filtered"u8)) - { - filtered = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("detected"u8)) - { - detected = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("citation"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - citation = ContentFilterProtectedMaterialCitationResult.DeserializeContentFilterProtectedMaterialCitationResult(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ContentFilterProtectedMaterialResult(filtered, detected, citation, serializedAdditionalRawData); - } - - 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(ContentFilterProtectedMaterialResult)} does not support writing '{options.Format}' format."); - } - } - - ContentFilterProtectedMaterialResult 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 DeserializeContentFilterProtectedMaterialResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ContentFilterProtectedMaterialResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ContentFilterProtectedMaterialResult FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterProtectedMaterialResult(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialResult.cs deleted file mode 100644 index 533e4b11b32b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterProtectedMaterialResult.cs +++ /dev/null @@ -1,78 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// The AzureContentFilterResultForChoiceProtectedMaterialCode. - public partial class ContentFilterProtectedMaterialResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// Whether the content detection resulted in a content filtering action. - /// Whether the labeled content category was detected in the content. - internal ContentFilterProtectedMaterialResult(bool filtered, bool detected) - { - Filtered = filtered; - Detected = detected; - } - - /// Initializes a new instance of . - /// Whether the content detection resulted in a content filtering action. - /// Whether the labeled content category was detected in the content. - /// If available, the citation details describing the associated license and its location. - /// Keeps track of any properties unknown to the library. - internal ContentFilterProtectedMaterialResult(bool filtered, bool detected, ContentFilterProtectedMaterialCitationResult citation, IDictionary serializedAdditionalRawData) - { - Filtered = filtered; - Detected = detected; - Citation = citation; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal ContentFilterProtectedMaterialResult() - { - } - - /// Whether the content detection resulted in a content filtering action. - public bool Filtered { get; } - /// Whether the labeled content category was detected in the content. - public bool Detected { get; } - /// If available, the citation details describing the associated license and its location. - public ContentFilterProtectedMaterialCitationResult Citation { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.Serialization.cs new file mode 100644 index 000000000000..66e09ecace67 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ContentFilterResult)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + writer.WritePropertyName("severity"u8); + writer.WriteStringValue(Severity.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ContentFilterResult 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(ContentFilterResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterResult(document.RootElement, options); + } + + internal static ContentFilterResult DeserializeContentFilterResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool filtered = default; + ContentFilterSeverity severity = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filtered"u8)) + { + filtered = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("severity"u8)) + { + severity = new ContentFilterSeverity(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterResult(filtered, severity, serializedAdditionalRawData); + } + + 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(ContentFilterResult)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterResult 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 DeserializeContentFilterResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeContentFilterResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverityResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.cs similarity index 57% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverityResult.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.cs index 95f0fa1bca5a..ea7952376a34 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverityResult.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -7,11 +10,8 @@ namespace Azure.AI.OpenAI { - /// - /// A labeled content filter result item that indicates whether the content was filtered and what the qualitative - /// severity level of the content was, as evaluated against content filter configuration for the category. - /// - public partial class ContentFilterSeverityResult + /// Information about filtered content severity level and if it has been filtered or not. + public partial class ContentFilterResult { /// /// Keeps track of any properties unknown to the library. @@ -43,33 +43,36 @@ public partial class ContentFilterSeverityResult /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// Whether the content severity resulted in a content filtering action. - /// The labeled severity of the content. - internal ContentFilterSeverityResult(bool filtered, ContentFilterSeverity severity) + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// Ratings for the intensity and risk level of filtered content. + internal ContentFilterResult(bool filtered, ContentFilterSeverity severity) { Filtered = filtered; Severity = severity; } - /// Initializes a new instance of . - /// Whether the content severity resulted in a content filtering action. - /// The labeled severity of the content. + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// Ratings for the intensity and risk level of filtered content. /// Keeps track of any properties unknown to the library. - internal ContentFilterSeverityResult(bool filtered, ContentFilterSeverity severity, IDictionary serializedAdditionalRawData) + internal ContentFilterResult(bool filtered, ContentFilterSeverity severity, IDictionary serializedAdditionalRawData) { Filtered = filtered; Severity = severity; - SerializedAdditionalRawData = serializedAdditionalRawData; + _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal ContentFilterSeverityResult() + /// Initializes a new instance of for deserialization. + internal ContentFilterResult() { } - /// Whether the content severity resulted in a content filtering action. + /// A value indicating whether or not the content has been filtered. public bool Filtered { get; } + /// Ratings for the intensity and risk level of filtered content. + public ContentFilterSeverity Severity { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResults.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.Serialization.cs similarity index 55% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResults.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.Serialization.cs index c2378dd52216..549644d7cf19 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResults.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.Serialization.cs @@ -1,79 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.AI.OpenAI { - internal partial class InternalAzureContentFilterResultForPromptContentFilterResults : IJsonModel + public partial class ContentFilterResultDetailsForPrompt : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(InternalAzureContentFilterResultForPromptContentFilterResults)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ContentFilterResultDetailsForPrompt)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("sexual") != true && Optional.IsDefined(Sexual)) + if (Optional.IsDefined(Sexual)) { writer.WritePropertyName("sexual"u8); writer.WriteObjectValue(Sexual, options); } - if (SerializedAdditionalRawData?.ContainsKey("hate") != true && Optional.IsDefined(Hate)) - { - writer.WritePropertyName("hate"u8); - writer.WriteObjectValue(Hate, options); - } - if (SerializedAdditionalRawData?.ContainsKey("violence") != true && Optional.IsDefined(Violence)) + if (Optional.IsDefined(Violence)) { writer.WritePropertyName("violence"u8); writer.WriteObjectValue(Violence, options); } - if (SerializedAdditionalRawData?.ContainsKey("self_harm") != true && Optional.IsDefined(SelfHarm)) + if (Optional.IsDefined(Hate)) + { + writer.WritePropertyName("hate"u8); + writer.WriteObjectValue(Hate, options); + } + if (Optional.IsDefined(SelfHarm)) { writer.WritePropertyName("self_harm"u8); writer.WriteObjectValue(SelfHarm, options); } - if (SerializedAdditionalRawData?.ContainsKey("profanity") != true && Optional.IsDefined(Profanity)) + if (Optional.IsDefined(Profanity)) { writer.WritePropertyName("profanity"u8); writer.WriteObjectValue(Profanity, options); } - if (SerializedAdditionalRawData?.ContainsKey("custom_blocklists") != true && Optional.IsDefined(CustomBlocklists)) + if (Optional.IsDefined(CustomBlocklists)) { writer.WritePropertyName("custom_blocklists"u8); writer.WriteObjectValue(CustomBlocklists, options); } - if (SerializedAdditionalRawData?.ContainsKey("error") != true && Optional.IsDefined(Error)) + if (Optional.IsDefined(Error)) { writer.WritePropertyName("error"u8); - writer.WriteObjectValue(Error, options); + JsonSerializer.Serialize(writer, Error); } - if (SerializedAdditionalRawData?.ContainsKey("jailbreak") != true) + if (Optional.IsDefined(Jailbreak)) { writer.WritePropertyName("jailbreak"u8); writer.WriteObjectValue(Jailbreak, options); } - if (SerializedAdditionalRawData?.ContainsKey("indirect_attack") != true) + if (Optional.IsDefined(IndirectAttack)) { writer.WritePropertyName("indirect_attack"u8); writer.WriteObjectValue(IndirectAttack, options); } - if (SerializedAdditionalRawData != null) + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -88,19 +89,19 @@ void IJsonModel.W writer.WriteEndObject(); } - InternalAzureContentFilterResultForPromptContentFilterResults IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ContentFilterResultDetailsForPrompt 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(InternalAzureContentFilterResultForPromptContentFilterResults)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ContentFilterResultDetailsForPrompt)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureContentFilterResultForPromptContentFilterResults(document.RootElement, options); + return DeserializeContentFilterResultDetailsForPrompt(document.RootElement, options); } - internal static InternalAzureContentFilterResultForPromptContentFilterResults DeserializeInternalAzureContentFilterResultForPromptContentFilterResults(JsonElement element, ModelReaderWriterOptions options = null) + internal static ContentFilterResultDetailsForPrompt DeserializeContentFilterResultDetailsForPrompt(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -108,13 +109,13 @@ internal static InternalAzureContentFilterResultForPromptContentFilterResults De { return null; } - ContentFilterSeverityResult sexual = default; - ContentFilterSeverityResult hate = default; - ContentFilterSeverityResult violence = default; - ContentFilterSeverityResult selfHarm = default; + ContentFilterResult sexual = default; + ContentFilterResult violence = default; + ContentFilterResult hate = default; + ContentFilterResult selfHarm = default; ContentFilterDetectionResult profanity = default; - ContentFilterBlocklistResult customBlocklists = default; - InternalAzureContentFilterResultForPromptContentFilterResultsError error = default; + ContentFilterDetailedResults customBlocklists = default; + ResponseError error = default; ContentFilterDetectionResult jailbreak = default; ContentFilterDetectionResult indirectAttack = default; IDictionary serializedAdditionalRawData = default; @@ -127,25 +128,25 @@ internal static InternalAzureContentFilterResultForPromptContentFilterResults De { continue; } - sexual = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + sexual = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } - if (property.NameEquals("hate"u8)) + if (property.NameEquals("violence"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - hate = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + violence = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } - if (property.NameEquals("violence"u8)) + if (property.NameEquals("hate"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - violence = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + hate = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } if (property.NameEquals("self_harm"u8)) @@ -154,7 +155,7 @@ internal static InternalAzureContentFilterResultForPromptContentFilterResults De { continue; } - selfHarm = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + selfHarm = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } if (property.NameEquals("profanity"u8)) @@ -172,7 +173,7 @@ internal static InternalAzureContentFilterResultForPromptContentFilterResults De { continue; } - customBlocklists = ContentFilterBlocklistResult.DeserializeContentFilterBlocklistResult(property.Value, options); + customBlocklists = ContentFilterDetailedResults.DeserializeContentFilterDetailedResults(property.Value, options); continue; } if (property.NameEquals("error"u8)) @@ -181,30 +182,37 @@ internal static InternalAzureContentFilterResultForPromptContentFilterResults De { continue; } - error = InternalAzureContentFilterResultForPromptContentFilterResultsError.DeserializeInternalAzureContentFilterResultForPromptContentFilterResultsError(property.Value, options); + error = JsonSerializer.Deserialize(property.Value.GetRawText()); continue; } if (property.NameEquals("jailbreak"u8)) { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } jailbreak = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); continue; } if (property.NameEquals("indirect_attack"u8)) { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } indirectAttack = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureContentFilterResultForPromptContentFilterResults( + return new ContentFilterResultDetailsForPrompt( sexual, - hate, violence, + hate, selfHarm, profanity, customBlocklists, @@ -214,50 +222,51 @@ internal static InternalAzureContentFilterResultForPromptContentFilterResults De 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(InternalAzureContentFilterResultForPromptContentFilterResults)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ContentFilterResultDetailsForPrompt)} does not support writing '{options.Format}' format."); } } - InternalAzureContentFilterResultForPromptContentFilterResults IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ContentFilterResultDetailsForPrompt 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 DeserializeInternalAzureContentFilterResultForPromptContentFilterResults(document.RootElement, options); + return DeserializeContentFilterResultDetailsForPrompt(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterResultForPromptContentFilterResults)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ContentFilterResultDetailsForPrompt)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalAzureContentFilterResultForPromptContentFilterResults FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static ContentFilterResultDetailsForPrompt FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureContentFilterResultForPromptContentFilterResults(document.RootElement); + return DeserializeContentFilterResultDetailsForPrompt(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.cs new file mode 100644 index 000000000000..acec97c64cc9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Information about content filtering evaluated against input data to Azure OpenAI. + public partial class ContentFilterResultDetailsForPrompt + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ContentFilterResultDetailsForPrompt() + { + } + + /// Initializes a new instance of . + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Describes detection results against configured custom blocklists. + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + /// Whether a jailbreak attempt was detected in the prompt. + /// Whether an indirect attack was detected in the prompt. + /// Keeps track of any properties unknown to the library. + internal ContentFilterResultDetailsForPrompt(ContentFilterResult sexual, ContentFilterResult violence, ContentFilterResult hate, ContentFilterResult selfHarm, ContentFilterDetectionResult profanity, ContentFilterDetailedResults customBlocklists, ResponseError error, ContentFilterDetectionResult jailbreak, ContentFilterDetectionResult indirectAttack, IDictionary serializedAdditionalRawData) + { + Sexual = sexual; + Violence = violence; + Hate = hate; + SelfHarm = selfHarm; + Profanity = profanity; + CustomBlocklists = customBlocklists; + Error = error; + Jailbreak = jailbreak; + IndirectAttack = indirectAttack; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + public ContentFilterResult Sexual { get; } + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + public ContentFilterResult Violence { get; } + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + public ContentFilterResult Hate { get; } + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + public ContentFilterResult SelfHarm { get; } + /// Describes whether profanity was detected. + public ContentFilterDetectionResult Profanity { get; } + /// Describes detection results against configured custom blocklists. + public ContentFilterDetailedResults CustomBlocklists { get; } + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + public ResponseError Error { get; } + /// Whether a jailbreak attempt was detected in the prompt. + public ContentFilterDetectionResult Jailbreak { get; } + /// Whether an indirect attack was detected in the prompt. + public ContentFilterDetectionResult IndirectAttack { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseContentFilterResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.Serialization.cs similarity index 56% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseContentFilterResult.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.Serialization.cs index 5e9da43d62eb..e624904d153a 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseContentFilterResult.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.Serialization.cs @@ -1,79 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.AI.OpenAI { - public partial class ResponseContentFilterResult : IJsonModel + public partial class ContentFilterResultsForChoice : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ResponseContentFilterResult)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ContentFilterResultsForChoice)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("sexual") != true && Optional.IsDefined(Sexual)) + if (Optional.IsDefined(Sexual)) { writer.WritePropertyName("sexual"u8); writer.WriteObjectValue(Sexual, options); } - if (SerializedAdditionalRawData?.ContainsKey("hate") != true && Optional.IsDefined(Hate)) - { - writer.WritePropertyName("hate"u8); - writer.WriteObjectValue(Hate, options); - } - if (SerializedAdditionalRawData?.ContainsKey("violence") != true && Optional.IsDefined(Violence)) + if (Optional.IsDefined(Violence)) { writer.WritePropertyName("violence"u8); writer.WriteObjectValue(Violence, options); } - if (SerializedAdditionalRawData?.ContainsKey("self_harm") != true && Optional.IsDefined(SelfHarm)) + if (Optional.IsDefined(Hate)) + { + writer.WritePropertyName("hate"u8); + writer.WriteObjectValue(Hate, options); + } + if (Optional.IsDefined(SelfHarm)) { writer.WritePropertyName("self_harm"u8); writer.WriteObjectValue(SelfHarm, options); } - if (SerializedAdditionalRawData?.ContainsKey("profanity") != true && Optional.IsDefined(Profanity)) + if (Optional.IsDefined(Profanity)) { writer.WritePropertyName("profanity"u8); writer.WriteObjectValue(Profanity, options); } - if (SerializedAdditionalRawData?.ContainsKey("custom_blocklists") != true && Optional.IsDefined(CustomBlocklists)) + if (Optional.IsDefined(CustomBlocklists)) { writer.WritePropertyName("custom_blocklists"u8); writer.WriteObjectValue(CustomBlocklists, options); } - if (SerializedAdditionalRawData?.ContainsKey("error") != true && Optional.IsDefined(Error)) + if (Optional.IsDefined(Error)) { writer.WritePropertyName("error"u8); - writer.WriteObjectValue(Error, options); + JsonSerializer.Serialize(writer, Error); } - if (SerializedAdditionalRawData?.ContainsKey("protected_material_text") != true && Optional.IsDefined(ProtectedMaterialText)) + if (Optional.IsDefined(ProtectedMaterialText)) { writer.WritePropertyName("protected_material_text"u8); writer.WriteObjectValue(ProtectedMaterialText, options); } - if (SerializedAdditionalRawData?.ContainsKey("protected_material_code") != true && Optional.IsDefined(ProtectedMaterialCode)) + if (Optional.IsDefined(ProtectedMaterialCode)) { writer.WritePropertyName("protected_material_code"u8); writer.WriteObjectValue(ProtectedMaterialCode, options); } - if (SerializedAdditionalRawData != null) + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -88,19 +89,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR writer.WriteEndObject(); } - ResponseContentFilterResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ContentFilterResultsForChoice 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(ResponseContentFilterResult)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ContentFilterResultsForChoice)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResponseContentFilterResult(document.RootElement, options); + return DeserializeContentFilterResultsForChoice(document.RootElement, options); } - internal static ResponseContentFilterResult DeserializeResponseContentFilterResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static ContentFilterResultsForChoice DeserializeContentFilterResultsForChoice(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -108,15 +109,15 @@ internal static ResponseContentFilterResult DeserializeResponseContentFilterResu { return null; } - ContentFilterSeverityResult sexual = default; - ContentFilterSeverityResult hate = default; - ContentFilterSeverityResult violence = default; - ContentFilterSeverityResult selfHarm = default; + ContentFilterResult sexual = default; + ContentFilterResult violence = default; + ContentFilterResult hate = default; + ContentFilterResult selfHarm = default; ContentFilterDetectionResult profanity = default; - ContentFilterBlocklistResult customBlocklists = default; - InternalAzureContentFilterResultForPromptContentFilterResultsError error = default; + ContentFilterDetailedResults customBlocklists = default; + ResponseError error = default; ContentFilterDetectionResult protectedMaterialText = default; - ContentFilterProtectedMaterialResult protectedMaterialCode = default; + ContentFilterCitedDetectionResult protectedMaterialCode = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -127,25 +128,25 @@ internal static ResponseContentFilterResult DeserializeResponseContentFilterResu { continue; } - sexual = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + sexual = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } - if (property.NameEquals("hate"u8)) + if (property.NameEquals("violence"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - hate = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + violence = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } - if (property.NameEquals("violence"u8)) + if (property.NameEquals("hate"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - violence = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + hate = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } if (property.NameEquals("self_harm"u8)) @@ -154,7 +155,7 @@ internal static ResponseContentFilterResult DeserializeResponseContentFilterResu { continue; } - selfHarm = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + selfHarm = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } if (property.NameEquals("profanity"u8)) @@ -172,7 +173,7 @@ internal static ResponseContentFilterResult DeserializeResponseContentFilterResu { continue; } - customBlocklists = ContentFilterBlocklistResult.DeserializeContentFilterBlocklistResult(property.Value, options); + customBlocklists = ContentFilterDetailedResults.DeserializeContentFilterDetailedResults(property.Value, options); continue; } if (property.NameEquals("error"u8)) @@ -181,7 +182,7 @@ internal static ResponseContentFilterResult DeserializeResponseContentFilterResu { continue; } - error = InternalAzureContentFilterResultForPromptContentFilterResultsError.DeserializeInternalAzureContentFilterResultForPromptContentFilterResultsError(property.Value, options); + error = JsonSerializer.Deserialize(property.Value.GetRawText()); continue; } if (property.NameEquals("protected_material_text"u8)) @@ -199,20 +200,19 @@ internal static ResponseContentFilterResult DeserializeResponseContentFilterResu { continue; } - protectedMaterialCode = ContentFilterProtectedMaterialResult.DeserializeContentFilterProtectedMaterialResult(property.Value, options); + protectedMaterialCode = ContentFilterCitedDetectionResult.DeserializeContentFilterCitedDetectionResult(property.Value, options); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new ResponseContentFilterResult( + return new ContentFilterResultsForChoice( sexual, - hate, violence, + hate, selfHarm, profanity, customBlocklists, @@ -222,49 +222,51 @@ internal static ResponseContentFilterResult DeserializeResponseContentFilterResu 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(ResponseContentFilterResult)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ContentFilterResultsForChoice)} does not support writing '{options.Format}' format."); } } - ResponseContentFilterResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ContentFilterResultsForChoice 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 DeserializeResponseContentFilterResult(document.RootElement, options); + return DeserializeContentFilterResultsForChoice(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ResponseContentFilterResult)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ContentFilterResultsForChoice)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ResponseContentFilterResult FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static ContentFilterResultsForChoice FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeResponseContentFilterResult(document.RootElement); + return DeserializeContentFilterResultsForChoice(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.cs new file mode 100644 index 000000000000..4f0ffaf66415 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Information about content filtering evaluated against generated model output. + public partial class ContentFilterResultsForChoice + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ContentFilterResultsForChoice() + { + } + + /// Initializes a new instance of . + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Describes detection results against configured custom blocklists. + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + /// Information about detection of protected text material. + /// Information about detection of protected code material. + /// Keeps track of any properties unknown to the library. + internal ContentFilterResultsForChoice(ContentFilterResult sexual, ContentFilterResult violence, ContentFilterResult hate, ContentFilterResult selfHarm, ContentFilterDetectionResult profanity, ContentFilterDetailedResults customBlocklists, ResponseError error, ContentFilterDetectionResult protectedMaterialText, ContentFilterCitedDetectionResult protectedMaterialCode, IDictionary serializedAdditionalRawData) + { + Sexual = sexual; + Violence = violence; + Hate = hate; + SelfHarm = selfHarm; + Profanity = profanity; + CustomBlocklists = customBlocklists; + Error = error; + ProtectedMaterialText = protectedMaterialText; + ProtectedMaterialCode = protectedMaterialCode; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + public ContentFilterResult Sexual { get; } + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + public ContentFilterResult Violence { get; } + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + public ContentFilterResult Hate { get; } + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + public ContentFilterResult SelfHarm { get; } + /// Describes whether profanity was detected. + public ContentFilterDetectionResult Profanity { get; } + /// Describes detection results against configured custom blocklists. + public ContentFilterDetailedResults CustomBlocklists { get; } + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + public ResponseError Error { get; } + /// Information about detection of protected text material. + public ContentFilterDetectionResult ProtectedMaterialText { get; } + /// Information about detection of protected code material. + public ContentFilterCitedDetectionResult ProtectedMaterialCode { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.Serialization.cs new file mode 100644 index 000000000000..27cdee78bdf5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterResultsForPrompt : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ContentFilterResultsForPrompt)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("prompt_index"u8); + writer.WriteNumberValue(PromptIndex); + writer.WritePropertyName("content_filter_results"u8); + writer.WriteObjectValue(ContentFilterResults, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ContentFilterResultsForPrompt 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(ContentFilterResultsForPrompt)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterResultsForPrompt(document.RootElement, options); + } + + internal static ContentFilterResultsForPrompt DeserializeContentFilterResultsForPrompt(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int promptIndex = default; + ContentFilterResultDetailsForPrompt contentFilterResults = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("prompt_index"u8)) + { + promptIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("content_filter_results"u8)) + { + contentFilterResults = ContentFilterResultDetailsForPrompt.DeserializeContentFilterResultDetailsForPrompt(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterResultsForPrompt(promptIndex, contentFilterResults, serializedAdditionalRawData); + } + + 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(ContentFilterResultsForPrompt)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterResultsForPrompt 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 DeserializeContentFilterResultsForPrompt(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterResultsForPrompt)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterResultsForPrompt FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeContentFilterResultsForPrompt(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.cs new file mode 100644 index 000000000000..4e411955a776 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Content filtering results for a single prompt in the request. + public partial class ContentFilterResultsForPrompt + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The index of this prompt in the set of prompt results. + /// Content filtering results for this prompt. + /// is null. + internal ContentFilterResultsForPrompt(int promptIndex, ContentFilterResultDetailsForPrompt contentFilterResults) + { + Argument.AssertNotNull(contentFilterResults, nameof(contentFilterResults)); + + PromptIndex = promptIndex; + ContentFilterResults = contentFilterResults; + } + + /// Initializes a new instance of . + /// The index of this prompt in the set of prompt results. + /// Content filtering results for this prompt. + /// Keeps track of any properties unknown to the library. + internal ContentFilterResultsForPrompt(int promptIndex, ContentFilterResultDetailsForPrompt contentFilterResults, IDictionary serializedAdditionalRawData) + { + PromptIndex = promptIndex; + ContentFilterResults = contentFilterResults; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ContentFilterResultsForPrompt() + { + } + + /// The index of this prompt in the set of prompt results. + public int PromptIndex { get; } + /// Content filtering results for this prompt. + public ContentFilterResultDetailsForPrompt ContentFilterResults { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverity.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverity.cs index 91a9f01a8528..4c49dd0aec22 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverity.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverity.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -7,7 +10,7 @@ namespace Azure.AI.OpenAI { - /// The AzureContentFilterSeverityResultSeverity. + /// Ratings for the intensity and risk level of harmful content. public readonly partial struct ContentFilterSeverity : IEquatable { private readonly string _value; @@ -24,19 +27,36 @@ public ContentFilterSeverity(string value) private const string MediumValue = "medium"; private const string HighValue = "high"; - /// safe. + /// + /// Content may be related to violence, self-harm, sexual, or hate categories but the terms + /// are used in general, journalistic, scientific, medical, and similar professional contexts, + /// which are appropriate for most audiences. + /// public static ContentFilterSeverity Safe { get; } = new ContentFilterSeverity(SafeValue); - /// low. + /// + /// Content that expresses prejudiced, judgmental, or opinionated views, includes offensive + /// use of language, stereotyping, use cases exploring a fictional world (for example, gaming, + /// literature) and depictions at low intensity. + /// public static ContentFilterSeverity Low { get; } = new ContentFilterSeverity(LowValue); - /// medium. + /// + /// Content that uses offensive, insulting, mocking, intimidating, or demeaning language + /// towards specific identity groups, includes depictions of seeking and executing harmful + /// instructions, fantasies, glorification, promotion of harm at medium intensity. + /// public static ContentFilterSeverity Medium { get; } = new ContentFilterSeverity(MediumValue); - /// high. + /// + /// Content that displays explicit and severe harmful instructions, actions, + /// damage, or abuse; includes endorsement, glorification, or promotion of severe + /// harmful acts, extreme or illegal forms of harm, radicalization, or non-consensual + /// power exchange or abuse. + /// public static ContentFilterSeverity High { get; } = new ContentFilterSeverity(HighValue); /// Determines if two values are the same. public static bool operator ==(ContentFilterSeverity left, ContentFilterSeverity right) => left.Equals(right); /// Determines if two values are not the same. public static bool operator !=(ContentFilterSeverity left, ContentFilterSeverity right) => !left.Equals(right); - /// Converts a string to a . + /// Converts a to a . public static implicit operator ContentFilterSeverity(string value) => new ContentFilterSeverity(value); /// diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverityResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverityResult.Serialization.cs deleted file mode 100644 index 6f7da3ac8cab..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverityResult.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - public partial class ContentFilterSeverityResult : 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(ContentFilterSeverityResult)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (SerializedAdditionalRawData?.ContainsKey("severity") != true) - { - writer.WritePropertyName("severity"u8); - writer.WriteStringValue(Severity.ToString()); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - ContentFilterSeverityResult 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(ContentFilterSeverityResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterSeverityResult(document.RootElement, options); - } - - internal static ContentFilterSeverityResult DeserializeContentFilterSeverityResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool filtered = default; - ContentFilterSeverity severity = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("filtered"u8)) - { - filtered = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("severity"u8)) - { - severity = new ContentFilterSeverity(property.Value.GetString()); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ContentFilterSeverityResult(filtered, severity, serializedAdditionalRawData); - } - - 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(ContentFilterSeverityResult)} does not support writing '{options.Format}' format."); - } - } - - ContentFilterSeverityResult 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 DeserializeContentFilterSeverityResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ContentFilterSeverityResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ContentFilterSeverityResult FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterSeverityResult(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CosmosChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CosmosChatDataSource.Serialization.cs deleted file mode 100644 index 7330e9d27e85..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/CosmosChatDataSource.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - public partial class CosmosChatDataSource : 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(CosmosChatDataSource)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("parameters") != true) - { - writer.WritePropertyName("parameters"u8); - writer.WriteObjectValue(InternalParameters, options); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - CosmosChatDataSource 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(CosmosChatDataSource)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCosmosChatDataSource(document.RootElement, options); - } - - internal static CosmosChatDataSource DeserializeCosmosChatDataSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - InternalAzureCosmosDBChatDataSourceParameters parameters = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("parameters"u8)) - { - parameters = InternalAzureCosmosDBChatDataSourceParameters.DeserializeInternalAzureCosmosDBChatDataSourceParameters(property.Value, options); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new CosmosChatDataSource(type, serializedAdditionalRawData, parameters); - } - - 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(CosmosChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - CosmosChatDataSource 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 DeserializeCosmosChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(CosmosChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new CosmosChatDataSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeCosmosChatDataSource(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CosmosChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CosmosChatDataSource.cs deleted file mode 100644 index 779961ba9e04..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/CosmosChatDataSource.cs +++ /dev/null @@ -1,14 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// Represents a data source configuration that will use an Azure CosmosDB resource. - public partial class CosmosChatDataSource : ChatDataSource - { - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.Serialization.cs new file mode 100644 index 000000000000..f788f96b1fa7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.Serialization.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CreateUploadRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(CreateUploadRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose.ToString()); + writer.WritePropertyName("bytes"u8); + writer.WriteNumberValue(Bytes); + writer.WritePropertyName("mime_type"u8); + writer.WriteStringValue(MimeType); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + CreateUploadRequest 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(CreateUploadRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCreateUploadRequest(document.RootElement, options); + } + + internal static CreateUploadRequest DeserializeCreateUploadRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string filename = default; + CreateUploadRequestPurpose purpose = default; + int bytes = default; + string mimeType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("purpose"u8)) + { + purpose = new CreateUploadRequestPurpose(property.Value.GetString()); + continue; + } + if (property.NameEquals("bytes"u8)) + { + bytes = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("mime_type"u8)) + { + mimeType = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CreateUploadRequest(filename, purpose, bytes, mimeType, serializedAdditionalRawData); + } + + 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(CreateUploadRequest)} does not support writing '{options.Format}' format."); + } + } + + CreateUploadRequest 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 DeserializeCreateUploadRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CreateUploadRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CreateUploadRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeCreateUploadRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.cs new file mode 100644 index 000000000000..a48d33b00bf1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The request body of an upload creation operation. + public partial class CreateUploadRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the file to upload. + /// + /// The intended purpose of the uploaded file. + /// + /// Use 'assistants' for Assistants and Message files, 'vision' for Assistants image file inputs, 'batch' for Batch API, and 'fine-tune' for Fine-tuning. + /// + /// The number of bytes in the file you are uploading. + /// + /// The MIME type of the file. + /// + /// This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. + /// + /// or is null. + public CreateUploadRequest(string filename, CreateUploadRequestPurpose purpose, int bytes, string mimeType) + { + Argument.AssertNotNull(filename, nameof(filename)); + Argument.AssertNotNull(mimeType, nameof(mimeType)); + + Filename = filename; + Purpose = purpose; + Bytes = bytes; + MimeType = mimeType; + } + + /// Initializes a new instance of . + /// The name of the file to upload. + /// + /// The intended purpose of the uploaded file. + /// + /// Use 'assistants' for Assistants and Message files, 'vision' for Assistants image file inputs, 'batch' for Batch API, and 'fine-tune' for Fine-tuning. + /// + /// The number of bytes in the file you are uploading. + /// + /// The MIME type of the file. + /// + /// This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. + /// + /// Keeps track of any properties unknown to the library. + internal CreateUploadRequest(string filename, CreateUploadRequestPurpose purpose, int bytes, string mimeType, IDictionary serializedAdditionalRawData) + { + Filename = filename; + Purpose = purpose; + Bytes = bytes; + MimeType = mimeType; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CreateUploadRequest() + { + } + + /// The name of the file to upload. + public string Filename { get; } + /// + /// The intended purpose of the uploaded file. + /// + /// Use 'assistants' for Assistants and Message files, 'vision' for Assistants image file inputs, 'batch' for Batch API, and 'fine-tune' for Fine-tuning. + /// + public CreateUploadRequestPurpose Purpose { get; } + /// The number of bytes in the file you are uploading. + public int Bytes { get; } + /// + /// The MIME type of the file. + /// + /// This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. + /// + public string MimeType { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequestPurpose.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequestPurpose.cs new file mode 100644 index 000000000000..c729a2f7df13 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequestPurpose.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The CreateUploadRequestPurpose. + public readonly partial struct CreateUploadRequestPurpose : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public CreateUploadRequestPurpose(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AssistantsValue = "assistants"; + private const string BatchValue = "batch"; + private const string FineTuneValue = "fine-tune"; + private const string VisionValue = "vision"; + + /// assistants. + public static CreateUploadRequestPurpose Assistants { get; } = new CreateUploadRequestPurpose(AssistantsValue); + /// batch. + public static CreateUploadRequestPurpose Batch { get; } = new CreateUploadRequestPurpose(BatchValue); + /// fine-tune. + public static CreateUploadRequestPurpose FineTune { get; } = new CreateUploadRequestPurpose(FineTuneValue); + /// vision. + public static CreateUploadRequestPurpose Vision { get; } = new CreateUploadRequestPurpose(VisionValue); + /// Determines if two values are the same. + public static bool operator ==(CreateUploadRequestPurpose left, CreateUploadRequestPurpose right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(CreateUploadRequestPurpose left, CreateUploadRequestPurpose right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator CreateUploadRequestPurpose(string value) => new CreateUploadRequestPurpose(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is CreateUploadRequestPurpose other && Equals(other); + /// + public bool Equals(CreateUploadRequestPurpose other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceAuthentication.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceAuthentication.Serialization.cs deleted file mode 100644 index da7309b6f794..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceAuthentication.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - [PersistableModelProxy(typeof(InternalUnknownAzureChatDataSourceAuthenticationOptions))] - public partial class DataSourceAuthentication : 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(DataSourceAuthentication)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - DataSourceAuthentication 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(DataSourceAuthentication)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataSourceAuthentication(document.RootElement, options); - } - - internal static DataSourceAuthentication DeserializeDataSourceAuthentication(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - if (element.TryGetProperty("type", out JsonElement discriminator)) - { - switch (discriminator.GetString()) - { - case "access_token": return InternalAzureChatDataSourceAccessTokenAuthenticationOptions.DeserializeInternalAzureChatDataSourceAccessTokenAuthenticationOptions(element, options); - case "api_key": return InternalAzureChatDataSourceApiKeyAuthenticationOptions.DeserializeInternalAzureChatDataSourceApiKeyAuthenticationOptions(element, options); - case "connection_string": return InternalAzureChatDataSourceConnectionStringAuthenticationOptions.DeserializeInternalAzureChatDataSourceConnectionStringAuthenticationOptions(element, options); - case "encoded_api_key": return InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.DeserializeInternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(element, options); - case "key_and_key_id": return InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.DeserializeInternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(element, options); - case "system_assigned_managed_identity": return InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.DeserializeInternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(element, options); - case "user_assigned_managed_identity": return InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.DeserializeInternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(element, options); - case "username_and_password": return InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.DeserializeInternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(element, options); - } - } - return InternalUnknownAzureChatDataSourceAuthenticationOptions.DeserializeInternalUnknownAzureChatDataSourceAuthenticationOptions(element, 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(DataSourceAuthentication)} does not support writing '{options.Format}' format."); - } - } - - DataSourceAuthentication 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 DeserializeDataSourceAuthentication(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataSourceAuthentication)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static DataSourceAuthentication FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeDataSourceAuthentication(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceQueryType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceQueryType.cs deleted file mode 100644 index 1f05c54d6d19..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceQueryType.cs +++ /dev/null @@ -1,57 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureSearchChatDataSourceParametersQueryType. - public readonly partial struct DataSourceQueryType : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public DataSourceQueryType(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string SimpleValue = "simple"; - private const string SemanticValue = "semantic"; - private const string VectorValue = "vector"; - private const string VectorSimpleHybridValue = "vector_simple_hybrid"; - private const string VectorSemanticHybridValue = "vector_semantic_hybrid"; - - /// simple. - public static DataSourceQueryType Simple { get; } = new DataSourceQueryType(SimpleValue); - /// semantic. - public static DataSourceQueryType Semantic { get; } = new DataSourceQueryType(SemanticValue); - /// vector. - public static DataSourceQueryType Vector { get; } = new DataSourceQueryType(VectorValue); - /// vector_simple_hybrid. - public static DataSourceQueryType VectorSimpleHybrid { get; } = new DataSourceQueryType(VectorSimpleHybridValue); - /// vector_semantic_hybrid. - public static DataSourceQueryType VectorSemanticHybrid { get; } = new DataSourceQueryType(VectorSemanticHybridValue); - /// Determines if two values are the same. - public static bool operator ==(DataSourceQueryType left, DataSourceQueryType right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(DataSourceQueryType left, DataSourceQueryType right) => !left.Equals(right); - /// Converts a string to a . - public static implicit operator DataSourceQueryType(string value) => new DataSourceQueryType(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is DataSourceQueryType other && Equals(other); - /// - public bool Equals(DataSourceQueryType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceVectorizer.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceVectorizer.Serialization.cs deleted file mode 100644 index c6e4b24822ee..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceVectorizer.Serialization.cs +++ /dev/null @@ -1,129 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - [PersistableModelProxy(typeof(InternalUnknownAzureChatDataSourceVectorizationSource))] - public partial class DataSourceVectorizer : 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(DataSourceVectorizer)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - DataSourceVectorizer 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(DataSourceVectorizer)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataSourceVectorizer(document.RootElement, options); - } - - internal static DataSourceVectorizer DeserializeDataSourceVectorizer(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - if (element.TryGetProperty("type", out JsonElement discriminator)) - { - switch (discriminator.GetString()) - { - case "deployment_name": return InternalAzureChatDataSourceDeploymentNameVectorizationSource.DeserializeInternalAzureChatDataSourceDeploymentNameVectorizationSource(element, options); - case "endpoint": return InternalAzureChatDataSourceEndpointVectorizationSource.DeserializeInternalAzureChatDataSourceEndpointVectorizationSource(element, options); - case "integrated": return InternalAzureChatDataSourceIntegratedVectorizationSource.DeserializeInternalAzureChatDataSourceIntegratedVectorizationSource(element, options); - case "model_id": return InternalAzureChatDataSourceModelIdVectorizationSource.DeserializeInternalAzureChatDataSourceModelIdVectorizationSource(element, options); - } - } - return InternalUnknownAzureChatDataSourceVectorizationSource.DeserializeInternalUnknownAzureChatDataSourceVectorizationSource(element, 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(DataSourceVectorizer)} does not support writing '{options.Format}' format."); - } - } - - DataSourceVectorizer 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 DeserializeDataSourceVectorizer(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataSourceVectorizer)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static DataSourceVectorizer FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeDataSourceVectorizer(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatDataSource.Serialization.cs deleted file mode 100644 index 5265a931500b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatDataSource.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - public partial class ElasticsearchChatDataSource : 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(ElasticsearchChatDataSource)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("parameters") != true) - { - writer.WritePropertyName("parameters"u8); - writer.WriteObjectValue(InternalParameters, options); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - ElasticsearchChatDataSource 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(ElasticsearchChatDataSource)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeElasticsearchChatDataSource(document.RootElement, options); - } - - internal static ElasticsearchChatDataSource DeserializeElasticsearchChatDataSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - InternalElasticsearchChatDataSourceParameters parameters = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("parameters"u8)) - { - parameters = InternalElasticsearchChatDataSourceParameters.DeserializeInternalElasticsearchChatDataSourceParameters(property.Value, options); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new ElasticsearchChatDataSource(type, serializedAdditionalRawData, parameters); - } - - 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(ElasticsearchChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - ElasticsearchChatDataSource 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 DeserializeElasticsearchChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ElasticsearchChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new ElasticsearchChatDataSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeElasticsearchChatDataSource(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatDataSource.cs deleted file mode 100644 index a3c0db4133ef..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatDataSource.cs +++ /dev/null @@ -1,14 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The ElasticsearchChatDataSource. - public partial class ElasticsearchChatDataSource : ChatDataSource - { - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..33f0c67f3110 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ElasticsearchChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ElasticsearchChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("parameters"u8); + writer.WriteObjectValue(Parameters, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ElasticsearchChatExtensionConfiguration 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(ElasticsearchChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeElasticsearchChatExtensionConfiguration(document.RootElement, options); + } + + internal static ElasticsearchChatExtensionConfiguration DeserializeElasticsearchChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ElasticsearchChatExtensionParameters parameters = default; + AzureChatExtensionType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("parameters"u8)) + { + parameters = ElasticsearchChatExtensionParameters.DeserializeElasticsearchChatExtensionParameters(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ElasticsearchChatExtensionConfiguration(type, serializedAdditionalRawData, parameters); + } + + 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(ElasticsearchChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + ElasticsearchChatExtensionConfiguration 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 DeserializeElasticsearchChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ElasticsearchChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeElasticsearchChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.cs new file mode 100644 index 000000000000..c02c027fb162 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat + /// extension. + /// + public partial class ElasticsearchChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// The parameters to use when configuring Elasticsearch®. + /// is null. + public ElasticsearchChatExtensionConfiguration(ElasticsearchChatExtensionParameters parameters) + { + Argument.AssertNotNull(parameters, nameof(parameters)); + + Type = AzureChatExtensionType.Elasticsearch; + Parameters = parameters; + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + /// The parameters to use when configuring Elasticsearch®. + internal ElasticsearchChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData, ElasticsearchChatExtensionParameters parameters) : base(type, serializedAdditionalRawData) + { + Parameters = parameters; + } + + /// Initializes a new instance of for deserialization. + internal ElasticsearchChatExtensionConfiguration() + { + } + + /// The parameters to use when configuring Elasticsearch®. + public ElasticsearchChatExtensionParameters Parameters { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalElasticsearchChatDataSourceParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.Serialization.cs similarity index 56% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/InternalElasticsearchChatDataSourceParameters.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.Serialization.cs index f526b7d19d4e..f08f3587fefe 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalElasticsearchChatDataSourceParameters.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.Serialization.cs @@ -1,99 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - internal partial class InternalElasticsearchChatDataSourceParameters : IJsonModel + public partial class ElasticsearchChatExtensionParameters : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(InternalElasticsearchChatDataSourceParameters)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionParameters)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("top_n_documents") != true && Optional.IsDefined(TopNDocuments)) + if (Optional.IsDefined(DocumentCount)) { writer.WritePropertyName("top_n_documents"u8); - writer.WriteNumberValue(TopNDocuments.Value); + writer.WriteNumberValue(DocumentCount.Value); } - if (SerializedAdditionalRawData?.ContainsKey("in_scope") != true && Optional.IsDefined(InScope)) + if (Optional.IsDefined(ShouldRestrictResultScope)) { writer.WritePropertyName("in_scope"u8); - writer.WriteBooleanValue(InScope.Value); + writer.WriteBooleanValue(ShouldRestrictResultScope.Value); } - if (SerializedAdditionalRawData?.ContainsKey("strictness") != true && Optional.IsDefined(Strictness)) + if (Optional.IsDefined(Strictness)) { writer.WritePropertyName("strictness"u8); writer.WriteNumberValue(Strictness.Value); } - if (SerializedAdditionalRawData?.ContainsKey("max_search_queries") != true && Optional.IsDefined(MaxSearchQueries)) + if (Optional.IsDefined(MaxSearchQueries)) { writer.WritePropertyName("max_search_queries"u8); writer.WriteNumberValue(MaxSearchQueries.Value); } - if (SerializedAdditionalRawData?.ContainsKey("allow_partial_result") != true && Optional.IsDefined(AllowPartialResult)) + if (Optional.IsDefined(AllowPartialResult)) { writer.WritePropertyName("allow_partial_result"u8); writer.WriteBooleanValue(AllowPartialResult.Value); } - if (SerializedAdditionalRawData?.ContainsKey("include_contexts") != true && Optional.IsCollectionDefined(_internalIncludeContexts)) + if (Optional.IsCollectionDefined(IncludeContexts)) { writer.WritePropertyName("include_contexts"u8); writer.WriteStartArray(); - foreach (var item in _internalIncludeContexts) + foreach (var item in IncludeContexts) { - writer.WriteStringValue(item); + writer.WriteStringValue(item.ToString()); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("endpoint") != true) - { - writer.WritePropertyName("endpoint"u8); - writer.WriteStringValue(Endpoint.AbsoluteUri); - } - if (SerializedAdditionalRawData?.ContainsKey("index_name") != true) - { - writer.WritePropertyName("index_name"u8); - writer.WriteStringValue(IndexName); - } - if (SerializedAdditionalRawData?.ContainsKey("authentication") != true) + if (Optional.IsDefined(Authentication)) { writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); + writer.WriteObjectValue(Authentication, options); } - if (SerializedAdditionalRawData?.ContainsKey("fields_mapping") != true && Optional.IsDefined(FieldMappings)) + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(Endpoint.AbsoluteUri); + writer.WritePropertyName("index_name"u8); + writer.WriteStringValue(IndexName); + if (Optional.IsDefined(FieldMappingOptions)) { writer.WritePropertyName("fields_mapping"u8); - writer.WriteObjectValue(FieldMappings, options); + writer.WriteObjectValue(FieldMappingOptions, options); } - if (SerializedAdditionalRawData?.ContainsKey("query_type") != true && Optional.IsDefined(QueryType)) + if (Optional.IsDefined(QueryType)) { writer.WritePropertyName("query_type"u8); writer.WriteStringValue(QueryType.Value.ToString()); } - if (SerializedAdditionalRawData?.ContainsKey("embedding_dependency") != true && Optional.IsDefined(VectorizationSource)) + if (Optional.IsDefined(EmbeddingDependency)) { writer.WritePropertyName("embedding_dependency"u8); - writer.WriteObjectValue(VectorizationSource, options); + writer.WriteObjectValue(EmbeddingDependency, options); } - if (SerializedAdditionalRawData != null) + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -108,19 +103,19 @@ void IJsonModel.Write(Utf8JsonWri writer.WriteEndObject(); } - InternalElasticsearchChatDataSourceParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ElasticsearchChatExtensionParameters 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(InternalElasticsearchChatDataSourceParameters)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionParameters)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalElasticsearchChatDataSourceParameters(document.RootElement, options); + return DeserializeElasticsearchChatExtensionParameters(document.RootElement, options); } - internal static InternalElasticsearchChatDataSourceParameters DeserializeInternalElasticsearchChatDataSourceParameters(JsonElement element, ModelReaderWriterOptions options = null) + internal static ElasticsearchChatExtensionParameters DeserializeElasticsearchChatExtensionParameters(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -133,13 +128,13 @@ internal static InternalElasticsearchChatDataSourceParameters DeserializeInterna int? strictness = default; int? maxSearchQueries = default; bool? allowPartialResult = default; - IList includeContexts = default; + IList includeContexts = default; + OnYourDataAuthenticationOptions authentication = default; Uri endpoint = default; string indexName = default; - DataSourceAuthentication authentication = default; - DataSourceFieldMappings fieldsMapping = default; - DataSourceQueryType? queryType = default; - DataSourceVectorizer embeddingDependency = default; + ElasticsearchIndexFieldMappingOptions fieldsMapping = default; + ElasticsearchQueryType? queryType = default; + OnYourDataVectorizationSource embeddingDependency = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -195,14 +190,23 @@ internal static InternalElasticsearchChatDataSourceParameters DeserializeInterna { continue; } - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(item.GetString()); + array.Add(new OnYourDataContextProperty(item.GetString())); } includeContexts = array; continue; } + if (property.NameEquals("authentication"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + authentication = OnYourDataAuthenticationOptions.DeserializeOnYourDataAuthenticationOptions(property.Value, options); + continue; + } if (property.NameEquals("endpoint"u8)) { endpoint = new Uri(property.Value.GetString()); @@ -213,18 +217,13 @@ internal static InternalElasticsearchChatDataSourceParameters DeserializeInterna indexName = property.Value.GetString(); continue; } - if (property.NameEquals("authentication"u8)) - { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(property.Value, options); - continue; - } if (property.NameEquals("fields_mapping"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - fieldsMapping = DataSourceFieldMappings.DeserializeDataSourceFieldMappings(property.Value, options); + fieldsMapping = ElasticsearchIndexFieldMappingOptions.DeserializeElasticsearchIndexFieldMappingOptions(property.Value, options); continue; } if (property.NameEquals("query_type"u8)) @@ -233,7 +232,7 @@ internal static InternalElasticsearchChatDataSourceParameters DeserializeInterna { continue; } - queryType = new DataSourceQueryType(property.Value.GetString()); + queryType = new ElasticsearchQueryType(property.Value.GetString()); continue; } if (property.NameEquals("embedding_dependency"u8)) @@ -242,76 +241,76 @@ internal static InternalElasticsearchChatDataSourceParameters DeserializeInterna { continue; } - embeddingDependency = DataSourceVectorizer.DeserializeDataSourceVectorizer(property.Value, options); + embeddingDependency = OnYourDataVectorizationSource.DeserializeOnYourDataVectorizationSource(property.Value, options); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new InternalElasticsearchChatDataSourceParameters( + return new ElasticsearchChatExtensionParameters( topNDocuments, inScope, strictness, maxSearchQueries, allowPartialResult, - includeContexts ?? new ChangeTrackingList(), + includeContexts ?? new ChangeTrackingList(), + authentication, endpoint, indexName, - authentication, fieldsMapping, queryType, embeddingDependency, 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(InternalElasticsearchChatDataSourceParameters)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionParameters)} does not support writing '{options.Format}' format."); } } - InternalElasticsearchChatDataSourceParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ElasticsearchChatExtensionParameters 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 DeserializeInternalElasticsearchChatDataSourceParameters(document.RootElement, options); + return DeserializeElasticsearchChatExtensionParameters(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalElasticsearchChatDataSourceParameters)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionParameters)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalElasticsearchChatDataSourceParameters FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static ElasticsearchChatExtensionParameters FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalElasticsearchChatDataSourceParameters(document.RootElement); + return DeserializeElasticsearchChatExtensionParameters(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.cs new file mode 100644 index 000000000000..ce7080e5d85f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Parameters to use when configuring Elasticsearch® as an Azure OpenAI chat extension. The supported authentication types are KeyAndKeyId and EncodedAPIKey. + public partial class ElasticsearchChatExtensionParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The endpoint of Elasticsearch®. + /// The index name of Elasticsearch®. + /// or is null. + public ElasticsearchChatExtensionParameters(Uri endpoint, string indexName) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(indexName, nameof(indexName)); + + IncludeContexts = new ChangeTrackingList(); + Endpoint = endpoint; + IndexName = indexName; + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The endpoint of Elasticsearch®. + /// The index name of Elasticsearch®. + /// The index field mapping options of Elasticsearch®. + /// The query type of Elasticsearch®. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// Keeps track of any properties unknown to the library. + internal ElasticsearchChatExtensionParameters(int? documentCount, bool? shouldRestrictResultScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList includeContexts, OnYourDataAuthenticationOptions authentication, Uri endpoint, string indexName, ElasticsearchIndexFieldMappingOptions fieldMappingOptions, ElasticsearchQueryType? queryType, OnYourDataVectorizationSource embeddingDependency, IDictionary serializedAdditionalRawData) + { + DocumentCount = documentCount; + ShouldRestrictResultScope = shouldRestrictResultScope; + Strictness = strictness; + MaxSearchQueries = maxSearchQueries; + AllowPartialResult = allowPartialResult; + IncludeContexts = includeContexts; + Authentication = authentication; + Endpoint = endpoint; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + QueryType = queryType; + EmbeddingDependency = embeddingDependency; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ElasticsearchChatExtensionParameters() + { + } + + /// The configured top number of documents to feature for the configured query. + public int? DocumentCount { get; set; } + /// Whether queries should be restricted to use of indexed data. + public bool? ShouldRestrictResultScope { get; set; } + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + public int? Strictness { get; set; } + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + public int? MaxSearchQueries { get; set; } + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + public bool? AllowPartialResult { get; set; } + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + public IList IncludeContexts { get; } + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + public OnYourDataAuthenticationOptions Authentication { get; set; } + /// The endpoint of Elasticsearch®. + public Uri Endpoint { get; } + /// The index name of Elasticsearch®. + public string IndexName { get; } + /// The index field mapping options of Elasticsearch®. + public ElasticsearchIndexFieldMappingOptions FieldMappingOptions { get; set; } + /// The query type of Elasticsearch®. + public ElasticsearchQueryType? QueryType { get; set; } + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public OnYourDataVectorizationSource EmbeddingDependency { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.Serialization.cs new file mode 100644 index 000000000000..27b2455ca8a6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.Serialization.cs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ElasticsearchIndexFieldMappingOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ElasticsearchIndexFieldMappingOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(TitleFieldName)) + { + writer.WritePropertyName("title_field"u8); + writer.WriteStringValue(TitleFieldName); + } + if (Optional.IsDefined(UrlFieldName)) + { + writer.WritePropertyName("url_field"u8); + writer.WriteStringValue(UrlFieldName); + } + if (Optional.IsDefined(FilepathFieldName)) + { + writer.WritePropertyName("filepath_field"u8); + writer.WriteStringValue(FilepathFieldName); + } + if (Optional.IsCollectionDefined(ContentFieldNames)) + { + writer.WritePropertyName("content_fields"u8); + writer.WriteStartArray(); + foreach (var item in ContentFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(ContentFieldSeparator)) + { + writer.WritePropertyName("content_fields_separator"u8); + writer.WriteStringValue(ContentFieldSeparator); + } + if (Optional.IsCollectionDefined(VectorFieldNames)) + { + writer.WritePropertyName("vector_fields"u8); + writer.WriteStartArray(); + foreach (var item in VectorFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ElasticsearchIndexFieldMappingOptions 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(ElasticsearchIndexFieldMappingOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeElasticsearchIndexFieldMappingOptions(document.RootElement, options); + } + + internal static ElasticsearchIndexFieldMappingOptions DeserializeElasticsearchIndexFieldMappingOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string titleField = default; + string urlField = default; + string filepathField = default; + IList contentFields = default; + string contentFieldsSeparator = default; + IList vectorFields = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("title_field"u8)) + { + titleField = property.Value.GetString(); + continue; + } + if (property.NameEquals("url_field"u8)) + { + urlField = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath_field"u8)) + { + filepathField = property.Value.GetString(); + continue; + } + if (property.NameEquals("content_fields"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + contentFields = array; + continue; + } + if (property.NameEquals("content_fields_separator"u8)) + { + contentFieldsSeparator = property.Value.GetString(); + continue; + } + if (property.NameEquals("vector_fields"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorFields = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ElasticsearchIndexFieldMappingOptions( + titleField, + urlField, + filepathField, + contentFields ?? new ChangeTrackingList(), + contentFieldsSeparator, + vectorFields ?? new ChangeTrackingList(), + serializedAdditionalRawData); + } + + 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(ElasticsearchIndexFieldMappingOptions)} does not support writing '{options.Format}' format."); + } + } + + ElasticsearchIndexFieldMappingOptions 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 DeserializeElasticsearchIndexFieldMappingOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ElasticsearchIndexFieldMappingOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ElasticsearchIndexFieldMappingOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeElasticsearchIndexFieldMappingOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceFieldMappings.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.cs similarity index 52% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceFieldMappings.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.cs index 7a7d022310ae..6213ad25cb49 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/DataSourceFieldMappings.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -5,10 +8,10 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - /// The AzureSearchChatDataSourceParametersFieldsMapping. - public partial class DataSourceFieldMappings + /// Optional settings to control how fields are processed when using a configured Elasticsearch® resource. + public partial class ElasticsearchIndexFieldMappingOptions { /// /// Keeps track of any properties unknown to the library. @@ -40,27 +43,45 @@ public partial class DataSourceFieldMappings /// /// /// - internal IDictionary SerializedAdditionalRawData { get; set; } + private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . + public ElasticsearchIndexFieldMappingOptions() + { + ContentFieldNames = new ChangeTrackingList(); + VectorFieldNames = new ChangeTrackingList(); + } + + /// Initializes a new instance of . /// The name of the index field to use as a title. /// The name of the index field to use as a URL. - /// The name of the index field to use as a filepath. + /// The name of the index field to use as a filepath. /// The names of index fields that should be treated as content. /// The separator pattern that content fields should use. /// The names of fields that represent vector data. - /// The names of fields that represent image vector data. /// Keeps track of any properties unknown to the library. - internal DataSourceFieldMappings(string titleFieldName, string urlFieldName, string filePathFieldName, IList contentFieldNames, string contentFieldSeparator, IList vectorFieldNames, IList imageVectorFieldNames, IDictionary serializedAdditionalRawData) + internal ElasticsearchIndexFieldMappingOptions(string titleFieldName, string urlFieldName, string filepathFieldName, IList contentFieldNames, string contentFieldSeparator, IList vectorFieldNames, IDictionary serializedAdditionalRawData) { TitleFieldName = titleFieldName; UrlFieldName = urlFieldName; - FilePathFieldName = filePathFieldName; + FilepathFieldName = filepathFieldName; ContentFieldNames = contentFieldNames; ContentFieldSeparator = contentFieldSeparator; VectorFieldNames = vectorFieldNames; - ImageVectorFieldNames = imageVectorFieldNames; - SerializedAdditionalRawData = serializedAdditionalRawData; + _serializedAdditionalRawData = serializedAdditionalRawData; } + + /// The name of the index field to use as a title. + public string TitleFieldName { get; set; } + /// The name of the index field to use as a URL. + public string UrlFieldName { get; set; } + /// The name of the index field to use as a filepath. + public string FilepathFieldName { get; set; } + /// The names of index fields that should be treated as content. + public IList ContentFieldNames { get; } + /// The separator pattern that content fields should use. + public string ContentFieldSeparator { get; set; } + /// The names of fields that represent vector data. + public IList VectorFieldNames { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchQueryType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchQueryType.cs new file mode 100644 index 000000000000..d8588a637f6d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchQueryType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The type of Elasticsearch® retrieval query that should be executed when using it as an Azure OpenAI chat extension. + public readonly partial struct ElasticsearchQueryType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ElasticsearchQueryType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SimpleValue = "simple"; + private const string VectorValue = "vector"; + + /// Represents the default, simple query parser. + public static ElasticsearchQueryType Simple { get; } = new ElasticsearchQueryType(SimpleValue); + /// Represents vector search over computed data. + public static ElasticsearchQueryType Vector { get; } = new ElasticsearchQueryType(VectorValue); + /// Determines if two values are the same. + public static bool operator ==(ElasticsearchQueryType left, ElasticsearchQueryType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ElasticsearchQueryType left, ElasticsearchQueryType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ElasticsearchQueryType(string value) => new ElasticsearchQueryType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ElasticsearchQueryType other && Equals(other); + /// + public bool Equals(ElasticsearchQueryType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingEncodingFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingEncodingFormat.cs new file mode 100644 index 000000000000..213af80cfdb5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingEncodingFormat.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Represents the available formats for embeddings data on responses. + public readonly partial struct EmbeddingEncodingFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public EmbeddingEncodingFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FloatValue = "float"; + private const string Base64Value = "base64"; + + /// Specifies that responses should provide arrays of floats for each embedding. + public static EmbeddingEncodingFormat Float { get; } = new EmbeddingEncodingFormat(FloatValue); + /// Specifies that responses should provide a base64-encoded string for each embedding. + public static EmbeddingEncodingFormat Base64 { get; } = new EmbeddingEncodingFormat(Base64Value); + /// Determines if two values are the same. + public static bool operator ==(EmbeddingEncodingFormat left, EmbeddingEncodingFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(EmbeddingEncodingFormat left, EmbeddingEncodingFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator EmbeddingEncodingFormat(string value) => new EmbeddingEncodingFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is EmbeddingEncodingFormat other && Equals(other); + /// + public bool Equals(EmbeddingEncodingFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.Serialization.cs similarity index 61% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.Serialization.cs index ea4cf4b4c062..cbb79f23908f 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.Serialization.cs @@ -11,29 +11,32 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.OpenAI.Assistants +namespace Azure.AI.OpenAI { - public partial class AssistantFile : IUtf8JsonSerializable, IJsonModel + internal partial class EmbeddingItem : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(AssistantFile)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(EmbeddingItem)} does not support writing '{format}' format."); } writer.WriteStartObject(); - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); + writer.WritePropertyName("embedding"u8); + writer.WriteStartArray(); + foreach (var item in Embedding) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object); - writer.WritePropertyName("created_at"u8); - writer.WriteNumberValue(CreatedAt, "U"); - writer.WritePropertyName("assistant_id"u8); - writer.WriteStringValue(AssistantId); + writer.WriteStringValue(Object.ToString()); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -52,19 +55,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt writer.WriteEndObject(); } - AssistantFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + EmbeddingItem 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(AssistantFile)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(EmbeddingItem)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAssistantFile(document.RootElement, options); + return DeserializeEmbeddingItem(document.RootElement, options); } - internal static AssistantFile DeserializeAssistantFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static EmbeddingItem DeserializeEmbeddingItem(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -72,32 +75,31 @@ internal static AssistantFile DeserializeAssistantFile(JsonElement element, Mode { return null; } - string id = default; - string @object = default; - DateTimeOffset createdAt = default; - string assistantId = default; + IReadOnlyList embedding = default; + int index = default; + EmbeddingItemObject @object = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (property.NameEquals("embedding"u8)) { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("object"u8)) - { - @object = property.Value.GetString(); + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetSingle()); + } + embedding = array; continue; } - if (property.NameEquals("created_at"u8)) + if (property.NameEquals("index"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + index = property.Value.GetInt32(); continue; } - if (property.NameEquals("assistant_id"u8)) + if (property.NameEquals("object"u8)) { - assistantId = property.Value.GetString(); + @object = new EmbeddingItemObject(property.Value.GetString()); continue; } if (options.Format != "W") @@ -106,46 +108,46 @@ internal static AssistantFile DeserializeAssistantFile(JsonElement element, Mode } } serializedAdditionalRawData = rawDataDictionary; - return new AssistantFile(id, @object, createdAt, assistantId, serializedAdditionalRawData); + return new EmbeddingItem(embedding, index, @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(AssistantFile)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(EmbeddingItem)} does not support writing '{options.Format}' format."); } } - AssistantFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + EmbeddingItem 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 DeserializeAssistantFile(document.RootElement, options); + return DeserializeEmbeddingItem(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(AssistantFile)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(EmbeddingItem)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static AssistantFile FromResponse(Response response) + internal static EmbeddingItem FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeAssistantFile(document.RootElement); + return DeserializeEmbeddingItem(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.cs new file mode 100644 index 000000000000..047042d2c0f5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.cs @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Representation of a single embeddings relatedness comparison. + internal partial class EmbeddingItem + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// List of embeddings value for the input prompt. These represent a measurement of the + /// vector-based relatedness of the provided input. + /// + /// Index of the prompt to which the EmbeddingItem corresponds. + /// is null. + internal EmbeddingItem(IEnumerable embedding, int index) + { + Argument.AssertNotNull(embedding, nameof(embedding)); + + Embedding = embedding.ToList(); + Index = index; + } + + /// Initializes a new instance of . + /// + /// List of embeddings value for the input prompt. These represent a measurement of the + /// vector-based relatedness of the provided input. + /// + /// Index of the prompt to which the EmbeddingItem corresponds. + /// The object type which is always 'embedding'. + /// Keeps track of any properties unknown to the library. + internal EmbeddingItem(IReadOnlyList embedding, int index, EmbeddingItemObject @object, IDictionary serializedAdditionalRawData) + { + Embedding = embedding; + Index = index; + Object = @object; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EmbeddingItem() + { + } + + /// + /// List of embeddings value for the input prompt. These represent a measurement of the + /// vector-based relatedness of the provided input. + /// + public IReadOnlyList Embedding { get; } + /// Index of the prompt to which the EmbeddingItem corresponds. + public int Index { get; } + /// The object type which is always 'embedding'. + public EmbeddingItemObject Object { get; } = EmbeddingItemObject.Embedding; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItemObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItemObject.cs new file mode 100644 index 000000000000..6d8867c0c41e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItemObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The EmbeddingItem_object. + internal readonly partial struct EmbeddingItemObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public EmbeddingItemObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EmbeddingValue = "embedding"; + + /// embedding. + public static EmbeddingItemObject Embedding { get; } = new EmbeddingItemObject(EmbeddingValue); + /// Determines if two values are the same. + public static bool operator ==(EmbeddingItemObject left, EmbeddingItemObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(EmbeddingItemObject left, EmbeddingItemObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator EmbeddingItemObject(string value) => new EmbeddingItemObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is EmbeddingItemObject other && Equals(other); + /// + public bool Equals(EmbeddingItemObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.Serialization.cs new file mode 100644 index 000000000000..89f93bf0e677 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class Embeddings : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OpenAI.Embeddings)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OpenAI.Embeddings 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(OpenAI.Embeddings)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return OpenAI.Embeddings.DeserializeEmbeddings(document.RootElement, options); + } + + internal static OpenAI.Embeddings DeserializeEmbeddings(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList data = default; + EmbeddingsUsage usage = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("data"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(EmbeddingItem.DeserializeEmbeddingItem(item, options)); + } + data = array; + continue; + } + if (property.NameEquals("usage"u8)) + { + usage = EmbeddingsUsage.DeserializeEmbeddingsUsage(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OpenAI.Embeddings(data, usage, serializedAdditionalRawData); + } + + 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(OpenAI.Embeddings)} does not support writing '{options.Format}' format."); + } + } + + OpenAI.Embeddings 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 OpenAI.Embeddings.DeserializeEmbeddings(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OpenAI.Embeddings)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OpenAI.Embeddings FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return OpenAI.Embeddings.DeserializeEmbeddings(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.cs new file mode 100644 index 000000000000..f6c3403bd45e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// Representation of the response data from an embeddings request. + /// Embeddings measure the relatedness of text strings and are commonly used for search, clustering, + /// recommendations, and other similar scenarios. + /// + internal partial class Embeddings + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Embedding values for the prompts submitted in the request. + /// Usage counts for tokens input using the embeddings API. + /// or is null. + internal Embeddings(IEnumerable data, EmbeddingsUsage usage) + { + Argument.AssertNotNull(data, nameof(data)); + Argument.AssertNotNull(usage, nameof(usage)); + + Data = data.ToList(); + Usage = usage; + } + + /// Initializes a new instance of . + /// Embedding values for the prompts submitted in the request. + /// Usage counts for tokens input using the embeddings API. + /// Keeps track of any properties unknown to the library. + internal Embeddings(IReadOnlyList data, EmbeddingsUsage usage, IDictionary serializedAdditionalRawData) + { + Data = data; + Usage = usage; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Embeddings() + { + } + + /// Embedding values for the prompts submitted in the request. + public IReadOnlyList Data { get; } + /// Usage counts for tokens input using the embeddings API. + public EmbeddingsUsage Usage { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.Serialization.cs new file mode 100644 index 000000000000..140629070ca3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.Serialization.cs @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class EmbeddingsOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(EmbeddingsOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(User)) + { + writer.WritePropertyName("user"u8); + writer.WriteStringValue(User); + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + writer.WritePropertyName("input"u8); + writer.WriteStartArray(); + foreach (var item in Input) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(EncodingFormat)) + { + writer.WritePropertyName("encoding_format"u8); + writer.WriteStringValue(EncodingFormat.Value.ToString()); + } + if (Optional.IsDefined(Dimensions)) + { + writer.WritePropertyName("dimensions"u8); + writer.WriteNumberValue(Dimensions.Value); + } + if (Optional.IsDefined(InputType)) + { + writer.WritePropertyName("input_type"u8); + writer.WriteStringValue(InputType); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + EmbeddingsOptions 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(EmbeddingsOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEmbeddingsOptions(document.RootElement, options); + } + + internal static EmbeddingsOptions DeserializeEmbeddingsOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string user = default; + string model = default; + IList input = default; + EmbeddingEncodingFormat? encodingFormat = default; + int? dimensions = default; + string inputType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("user"u8)) + { + user = property.Value.GetString(); + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (property.NameEquals("input"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + input = array; + continue; + } + if (property.NameEquals("encoding_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + encodingFormat = new EmbeddingEncodingFormat(property.Value.GetString()); + continue; + } + if (property.NameEquals("dimensions"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + dimensions = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("input_type"u8)) + { + inputType = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EmbeddingsOptions( + user, + model, + input, + encodingFormat, + dimensions, + inputType, + serializedAdditionalRawData); + } + + 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(EmbeddingsOptions)} does not support writing '{options.Format}' format."); + } + } + + EmbeddingsOptions 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 DeserializeEmbeddingsOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EmbeddingsOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static EmbeddingsOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeEmbeddingsOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.cs new file mode 100644 index 000000000000..7a25f39f4f5a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// The configuration information for an embeddings request. + /// Embeddings measure the relatedness of text strings and are commonly used for search, clustering, + /// recommendations, and other similar scenarios. + /// + public partial class EmbeddingsOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// Input texts to get embeddings for, encoded as a an array of strings. + /// Each input must not exceed 2048 tokens in length. + /// + /// Unless you are embedding code, we suggest replacing newlines (\n) in your input with a single space, + /// as we have observed inferior results when newlines are present. + /// + /// is null. + public EmbeddingsOptions(IEnumerable input) + { + Argument.AssertNotNull(input, nameof(input)); + + Input = input.ToList(); + } + + /// Initializes a new instance of . + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + /// + /// The model name to provide as part of this embeddings request. + /// Not applicable to Azure OpenAI, where deployment information should be included in the Azure + /// resource URI that's connected to. + /// + /// + /// Input texts to get embeddings for, encoded as a an array of strings. + /// Each input must not exceed 2048 tokens in length. + /// + /// Unless you are embedding code, we suggest replacing newlines (\n) in your input with a single space, + /// as we have observed inferior results when newlines are present. + /// + /// The response encoding format to use for embedding data. + /// The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. + /// When using Azure OpenAI, specifies the input type to use for embedding search. + /// Keeps track of any properties unknown to the library. + internal EmbeddingsOptions(string user, string deploymentName, IList input, EmbeddingEncodingFormat? encodingFormat, int? dimensions, string inputType, IDictionary serializedAdditionalRawData) + { + User = user; + DeploymentName = deploymentName; + Input = input; + EncodingFormat = encodingFormat; + Dimensions = dimensions; + InputType = inputType; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EmbeddingsOptions() + { + } + + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + public string User { get; set; } + /// + /// The model name to provide as part of this embeddings request. + /// Not applicable to Azure OpenAI, where deployment information should be included in the Azure + /// resource URI that's connected to. + /// + public string DeploymentName { get; set; } + /// + /// Input texts to get embeddings for, encoded as a an array of strings. + /// Each input must not exceed 2048 tokens in length. + /// + /// Unless you are embedding code, we suggest replacing newlines (\n) in your input with a single space, + /// as we have observed inferior results when newlines are present. + /// + public IList Input { get; } + /// The response encoding format to use for embedding data. + public EmbeddingEncodingFormat? EncodingFormat { get; set; } + /// The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. + public int? Dimensions { get; set; } + /// When using Azure OpenAI, specifies the input type to use for embedding search. + public string InputType { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.Serialization.cs new file mode 100644 index 000000000000..bd51b2789ae4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class EmbeddingsUsage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(EmbeddingsUsage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("prompt_tokens"u8); + writer.WriteNumberValue(PromptTokens); + writer.WritePropertyName("total_tokens"u8); + writer.WriteNumberValue(TotalTokens); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + EmbeddingsUsage 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(EmbeddingsUsage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEmbeddingsUsage(document.RootElement, options); + } + + internal static EmbeddingsUsage DeserializeEmbeddingsUsage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int promptTokens = default; + int totalTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("prompt_tokens"u8)) + { + promptTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("total_tokens"u8)) + { + totalTokens = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EmbeddingsUsage(promptTokens, totalTokens, serializedAdditionalRawData); + } + + 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(EmbeddingsUsage)} does not support writing '{options.Format}' format."); + } + } + + EmbeddingsUsage 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 DeserializeEmbeddingsUsage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EmbeddingsUsage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static EmbeddingsUsage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeEmbeddingsUsage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.cs new file mode 100644 index 000000000000..00f0ce06d636 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Measurement of the amount of tokens used in this request and response. + internal partial class EmbeddingsUsage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Number of tokens sent in the original request. + /// Total number of tokens transacted in this request/response. + internal EmbeddingsUsage(int promptTokens, int totalTokens) + { + PromptTokens = promptTokens; + TotalTokens = totalTokens; + } + + /// Initializes a new instance of . + /// Number of tokens sent in the original request. + /// Total number of tokens transacted in this request/response. + /// Keeps track of any properties unknown to the library. + internal EmbeddingsUsage(int promptTokens, int totalTokens, IDictionary serializedAdditionalRawData) + { + PromptTokens = promptTokens; + TotalTokens = totalTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EmbeddingsUsage() + { + } + + /// Number of tokens sent in the original request. + public int PromptTokens { get; } + /// Total number of tokens transacted in this request/response. + public int TotalTokens { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.Serialization.cs new file mode 100644 index 000000000000..f707b65a7c65 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class FileDeletionStatus : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(FileDeletionStatus)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("deleted"u8); + writer.WriteBooleanValue(Deleted); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + FileDeletionStatus 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(FileDeletionStatus)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileDeletionStatus(document.RootElement, options); + } + + internal static FileDeletionStatus DeserializeFileDeletionStatus(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + bool deleted = default; + FileDeletionStatusObject @object = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("deleted"u8)) + { + deleted = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new FileDeletionStatusObject(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileDeletionStatus(id, deleted, @object, serializedAdditionalRawData); + } + + 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(FileDeletionStatus)} does not support writing '{options.Format}' format."); + } + } + + FileDeletionStatus 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 DeserializeFileDeletionStatus(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileDeletionStatus)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FileDeletionStatus FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFileDeletionStatus(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.cs new file mode 100644 index 000000000000..1ffbf9b3ebf9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A status response from a file deletion operation. + public partial class FileDeletionStatus + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// is null. + internal FileDeletionStatus(string id, bool deleted) + { + Argument.AssertNotNull(id, nameof(id)); + + Id = id; + Deleted = deleted; + } + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// The object type, which is always 'file'. + /// Keeps track of any properties unknown to the library. + internal FileDeletionStatus(string id, bool deleted, FileDeletionStatusObject @object, IDictionary serializedAdditionalRawData) + { + Id = id; + Deleted = deleted; + Object = @object; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FileDeletionStatus() + { + } + + /// The ID of the resource specified for deletion. + public string Id { get; } + /// A value indicating whether deletion was successful. + public bool Deleted { get; } + /// The object type, which is always 'file'. + public FileDeletionStatusObject Object { get; } = FileDeletionStatusObject.File; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatusObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatusObject.cs new file mode 100644 index 000000000000..7023f72b90f5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatusObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The FileDeletionStatus_object. + public readonly partial struct FileDeletionStatusObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileDeletionStatusObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FileValue = "file"; + + /// file. + public static FileDeletionStatusObject File { get; } = new FileDeletionStatusObject(FileValue); + /// Determines if two values are the same. + public static bool operator ==(FileDeletionStatusObject left, FileDeletionStatusObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileDeletionStatusObject left, FileDeletionStatusObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FileDeletionStatusObject(string value) => new FileDeletionStatusObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileDeletionStatusObject other && Equals(other); + /// + public bool Equals(FileDeletionStatusObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.Serialization.cs new file mode 100644 index 000000000000..0b3f7339e23a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class FileListResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(FileListResponse)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + FileListResponse 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(FileListResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileListResponse(document.RootElement, options); + } + + internal static FileListResponse DeserializeFileListResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + FileListResponseObject @object = default; + IReadOnlyList data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("object"u8)) + { + @object = new FileListResponseObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("data"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(OpenAIFile.DeserializeOpenAIFile(item, options)); + } + data = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileListResponse(@object, data, serializedAdditionalRawData); + } + + 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(FileListResponse)} does not support writing '{options.Format}' format."); + } + } + + FileListResponse 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 DeserializeFileListResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileListResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FileListResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFileListResponse(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.cs new file mode 100644 index 000000000000..bcd03986f3fc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The response data from a file list operation. + public partial class FileListResponse + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The files returned for the request. + /// is null. + internal FileListResponse(IEnumerable data) + { + Argument.AssertNotNull(data, nameof(data)); + + Data = data.ToList(); + } + + /// Initializes a new instance of . + /// The object type, which is always 'list'. + /// The files returned for the request. + /// Keeps track of any properties unknown to the library. + internal FileListResponse(FileListResponseObject @object, IReadOnlyList data, IDictionary serializedAdditionalRawData) + { + Object = @object; + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FileListResponse() + { + } + + /// The object type, which is always 'list'. + public FileListResponseObject Object { get; } = FileListResponseObject.List; + + /// The files returned for the request. + public IReadOnlyList Data { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponseObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponseObject.cs new file mode 100644 index 000000000000..4d72d8c6702d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponseObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The FileListResponse_object. + public readonly partial struct FileListResponseObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileListResponseObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ListValue = "list"; + + /// list. + public static FileListResponseObject List { get; } = new FileListResponseObject(ListValue); + /// Determines if two values are the same. + public static bool operator ==(FileListResponseObject left, FileListResponseObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileListResponseObject left, FileListResponseObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FileListResponseObject(string value) => new FileListResponseObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileListResponseObject other && Equals(other); + /// + public bool Equals(FileListResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FilePurpose.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FilePurpose.cs new file mode 100644 index 000000000000..a77cbe48fa1b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FilePurpose.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The possible values denoting the intended usage of a file. + public readonly partial struct FilePurpose : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FilePurpose(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FineTuneValue = "fine-tune"; + private const string FineTuneResultsValue = "fine-tune-results"; + private const string AssistantsValue = "assistants"; + private const string AssistantsOutputValue = "assistants_output"; + private const string BatchValue = "batch"; + private const string BatchOutputValue = "batch_output"; + private const string VisionValue = "vision"; + + /// Indicates a file is used for fine tuning input. + public static FilePurpose FineTune { get; } = new FilePurpose(FineTuneValue); + /// Indicates a file is used for fine tuning results. + public static FilePurpose FineTuneResults { get; } = new FilePurpose(FineTuneResultsValue); + /// Indicates a file is used as input to assistants. + public static FilePurpose Assistants { get; } = new FilePurpose(AssistantsValue); + /// Indicates a file is used as output by assistants. + public static FilePurpose AssistantsOutput { get; } = new FilePurpose(AssistantsOutputValue); + /// Indicates a file is used as input to . + public static FilePurpose Batch { get; } = new FilePurpose(BatchValue); + /// Indicates a file is used as output by a vector store batch operation. + public static FilePurpose BatchOutput { get; } = new FilePurpose(BatchOutputValue); + /// Indicates a file is used as input to a vision operation. + public static FilePurpose Vision { get; } = new FilePurpose(VisionValue); + /// Determines if two values are the same. + public static bool operator ==(FilePurpose left, FilePurpose right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FilePurpose left, FilePurpose right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FilePurpose(string value) => new FilePurpose(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FilePurpose other && Equals(other); + /// + public bool Equals(FilePurpose other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileState.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileState.cs new file mode 100644 index 000000000000..637802d9dee3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileState.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The state of the file. + public readonly partial struct FileState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UploadedValue = "uploaded"; + private const string PendingValue = "pending"; + private const string RunningValue = "running"; + private const string ProcessedValue = "processed"; + private const string ErrorValue = "error"; + private const string DeletingValue = "deleting"; + private const string DeletedValue = "deleted"; + + /// + /// The file has been uploaded but it's not yet processed. This state is not returned by Azure OpenAI and exposed only for + /// compatibility. It can be categorized as an inactive state. + /// + public static FileState Uploaded { get; } = new FileState(UploadedValue); + /// The operation was created and is not queued to be processed in the future. It can be categorized as an inactive state. + public static FileState Pending { get; } = new FileState(PendingValue); + /// The operation has started to be processed. It can be categorized as an active state. + public static FileState Running { get; } = new FileState(RunningValue); + /// The operation has successfully processed and is ready for consumption. It can be categorized as a terminal state. + public static FileState Processed { get; } = new FileState(ProcessedValue); + /// The operation has completed processing with a failure and cannot be further consumed. It can be categorized as a terminal state. + public static FileState Error { get; } = new FileState(ErrorValue); + /// + /// The entity is in the process to be deleted. This state is not returned by Azure OpenAI and exposed only for compatibility. + /// It can be categorized as an active state. + /// + public static FileState Deleting { get; } = new FileState(DeletingValue); + /// + /// The entity has been deleted but may still be referenced by other entities predating the deletion. It can be categorized as a + /// terminal state. + /// + public static FileState Deleted { get; } = new FileState(DeletedValue); + /// Determines if two values are the same. + public static bool operator ==(FileState left, FileState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileState left, FileState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FileState(string value) => new FileState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileState other && Equals(other); + /// + public bool Equals(FileState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.Serialization.cs new file mode 100644 index 000000000000..dce00585fff1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class FunctionCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(FunctionCall)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + writer.WritePropertyName("arguments"u8); + writer.WriteStringValue(Arguments); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + FunctionCall 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(FunctionCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFunctionCall(document.RootElement, options); + } + + internal static FunctionCall DeserializeFunctionCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string arguments = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("arguments"u8)) + { + arguments = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FunctionCall(name, arguments, serializedAdditionalRawData); + } + + 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(FunctionCall)} does not support writing '{options.Format}' format."); + } + } + + FunctionCall 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 DeserializeFunctionCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FunctionCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FunctionCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFunctionCall(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.cs new file mode 100644 index 000000000000..2a2534aebe1e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The name and arguments of a function that should be called, as generated by the model. + public partial class FunctionCall + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the function to call. + /// + /// The arguments to call the function with, as generated by the model in JSON format. + /// Note that the model does not always generate valid JSON, and may hallucinate parameters + /// not defined by your function schema. Validate the arguments in your code before calling + /// your function. + /// + /// or is null. + public FunctionCall(string name, string arguments) + { + Argument.AssertNotNull(name, nameof(name)); + Argument.AssertNotNull(arguments, nameof(arguments)); + + Name = name; + Arguments = arguments; + } + + /// Initializes a new instance of . + /// The name of the function to call. + /// + /// The arguments to call the function with, as generated by the model in JSON format. + /// Note that the model does not always generate valid JSON, and may hallucinate parameters + /// not defined by your function schema. Validate the arguments in your code before calling + /// your function. + /// + /// Keeps track of any properties unknown to the library. + internal FunctionCall(string name, string arguments, IDictionary serializedAdditionalRawData) + { + Name = name; + Arguments = arguments; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FunctionCall() + { + } + + /// The name of the function to call. + public string Name { get; set; } + /// + /// The arguments to call the function with, as generated by the model in JSON format. + /// Note that the model does not always generate valid JSON, and may hallucinate parameters + /// not defined by your function schema. Validate the arguments in your code before calling + /// your function. + /// + public string Arguments { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCallPreset.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCallPreset.cs new file mode 100644 index 000000000000..6e15f0039916 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCallPreset.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// + /// The collection of predefined behaviors for handling request-provided function information in a chat completions + /// operation. + /// + public readonly partial struct FunctionCallPreset : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FunctionCallPreset(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string NoneValue = "none"; + + /// + /// Specifies that the model may either use any of the functions provided in this chat completions request or + /// instead return a standard chat completions response as if no functions were provided. + /// + public static FunctionCallPreset Auto { get; } = new FunctionCallPreset(AutoValue); + /// + /// Specifies that the model should not respond with a function call and should instead provide a standard chat + /// completions response. Response content may still be influenced by the provided function information. + /// + public static FunctionCallPreset None { get; } = new FunctionCallPreset(NoneValue); + /// Determines if two values are the same. + public static bool operator ==(FunctionCallPreset left, FunctionCallPreset right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FunctionCallPreset left, FunctionCallPreset right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FunctionCallPreset(string value) => new FunctionCallPreset(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FunctionCallPreset other && Equals(other); + /// + public bool Equals(FunctionCallPreset other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.Serialization.cs new file mode 100644 index 000000000000..e9999febe97f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.Serialization.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class FunctionDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(FunctionDefinition)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + if (Optional.IsDefined(Parameters)) + { + writer.WritePropertyName("parameters"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Parameters); +#else + using (JsonDocument document = JsonDocument.Parse(Parameters)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + FunctionDefinition 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(FunctionDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFunctionDefinition(document.RootElement, options); + } + + internal static FunctionDefinition DeserializeFunctionDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string description = default; + BinaryData parameters = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("parameters"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parameters = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FunctionDefinition(name, description, parameters, serializedAdditionalRawData); + } + + 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(FunctionDefinition)} does not support writing '{options.Format}' format."); + } + } + + FunctionDefinition 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 DeserializeFunctionDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FunctionDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FunctionDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFunctionDefinition(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.cs new file mode 100644 index 000000000000..1de7bfba323c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The definition of a caller-specified function that chat completions may invoke in response to matching user input. + public partial class FunctionDefinition + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the function to be called. + /// is null. + public FunctionDefinition(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + /// Initializes a new instance of . + /// The name of the function to be called. + /// + /// A description of what the function does. The model will use this description when selecting the function and + /// interpreting its parameters. + /// + /// The parameters the function accepts, described as a JSON Schema object. + /// Keeps track of any properties unknown to the library. + internal FunctionDefinition(string name, string description, BinaryData parameters, IDictionary serializedAdditionalRawData) + { + Name = name; + Description = description; + Parameters = parameters; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FunctionDefinition() + { + } + + /// The name of the function to be called. + public string Name { get; } + /// + /// A description of what the function does. The model will use this description when selecting the function and + /// interpreting its parameters. + /// + public string Description { get; set; } + /// + /// The parameters the function accepts, described as a JSON Schema object. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Parameters { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.Serialization.cs new file mode 100644 index 000000000000..373fa127c97b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class FunctionName : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(FunctionName)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + FunctionName 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(FunctionName)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFunctionName(document.RootElement, options); + } + + internal static FunctionName DeserializeFunctionName(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FunctionName(name, serializedAdditionalRawData); + } + + 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(FunctionName)} does not support writing '{options.Format}' format."); + } + } + + FunctionName 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 DeserializeFunctionName(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FunctionName)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FunctionName FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeFunctionName(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.cs new file mode 100644 index 000000000000..14ca22fb4973 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A structure that specifies the exact name of a specific, request-provided function to use when processing a chat + /// completions operation. + /// + public partial class FunctionName + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the function to call. + /// is null. + public FunctionName(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + /// Initializes a new instance of . + /// The name of the function to call. + /// Keeps track of any properties unknown to the library. + internal FunctionName(string name, IDictionary serializedAdditionalRawData) + { + Name = name; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FunctionName() + { + } + + /// The name of the function to call. + public string Name { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseImageContentFilterResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.Serialization.cs similarity index 51% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseImageContentFilterResult.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.Serialization.cs index ea977b08966e..608585f71046 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseImageContentFilterResult.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.Serialization.cs @@ -1,54 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.AI.OpenAI { - public partial class ResponseImageContentFilterResult : IJsonModel + public partial class ImageGenerationContentFilterResults : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ResponseImageContentFilterResult)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationContentFilterResults)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("sexual") != true && Optional.IsDefined(Sexual)) + if (Optional.IsDefined(Sexual)) { writer.WritePropertyName("sexual"u8); writer.WriteObjectValue(Sexual, options); } - if (SerializedAdditionalRawData?.ContainsKey("violence") != true && Optional.IsDefined(Violence)) + if (Optional.IsDefined(Violence)) { writer.WritePropertyName("violence"u8); writer.WriteObjectValue(Violence, options); } - if (SerializedAdditionalRawData?.ContainsKey("hate") != true && Optional.IsDefined(Hate)) + if (Optional.IsDefined(Hate)) { writer.WritePropertyName("hate"u8); writer.WriteObjectValue(Hate, options); } - if (SerializedAdditionalRawData?.ContainsKey("self_harm") != true && Optional.IsDefined(SelfHarm)) + if (Optional.IsDefined(SelfHarm)) { writer.WritePropertyName("self_harm"u8); writer.WriteObjectValue(SelfHarm, options); } - if (SerializedAdditionalRawData != null) + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -63,19 +64,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, M writer.WriteEndObject(); } - ResponseImageContentFilterResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ImageGenerationContentFilterResults 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(ResponseImageContentFilterResult)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationContentFilterResults)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResponseImageContentFilterResult(document.RootElement, options); + return DeserializeImageGenerationContentFilterResults(document.RootElement, options); } - internal static ResponseImageContentFilterResult DeserializeResponseImageContentFilterResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static ImageGenerationContentFilterResults DeserializeImageGenerationContentFilterResults(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -83,10 +84,10 @@ internal static ResponseImageContentFilterResult DeserializeResponseImageContent { return null; } - ContentFilterSeverityResult sexual = default; - ContentFilterSeverityResult violence = default; - ContentFilterSeverityResult hate = default; - ContentFilterSeverityResult selfHarm = default; + ContentFilterResult sexual = default; + ContentFilterResult violence = default; + ContentFilterResult hate = default; + ContentFilterResult selfHarm = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -97,7 +98,7 @@ internal static ResponseImageContentFilterResult DeserializeResponseImageContent { continue; } - sexual = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + sexual = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } if (property.NameEquals("violence"u8)) @@ -106,7 +107,7 @@ internal static ResponseImageContentFilterResult DeserializeResponseImageContent { continue; } - violence = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + violence = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } if (property.NameEquals("hate"u8)) @@ -115,7 +116,7 @@ internal static ResponseImageContentFilterResult DeserializeResponseImageContent { continue; } - hate = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + hate = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } if (property.NameEquals("self_harm"u8)) @@ -124,62 +125,63 @@ internal static ResponseImageContentFilterResult DeserializeResponseImageContent { continue; } - selfHarm = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + selfHarm = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new ResponseImageContentFilterResult(sexual, violence, hate, selfHarm, serializedAdditionalRawData); + return new ImageGenerationContentFilterResults(sexual, violence, hate, selfHarm, 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(ResponseImageContentFilterResult)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationContentFilterResults)} does not support writing '{options.Format}' format."); } } - ResponseImageContentFilterResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ImageGenerationContentFilterResults 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 DeserializeResponseImageContentFilterResult(document.RootElement, options); + return DeserializeImageGenerationContentFilterResults(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ResponseImageContentFilterResult)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationContentFilterResults)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static ResponseImageContentFilterResult FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static ImageGenerationContentFilterResults FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeResponseImageContentFilterResult(document.RootElement); + return DeserializeImageGenerationContentFilterResults(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.cs new file mode 100644 index 000000000000..a9dd21aaaa9d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Describes the content filtering result for the image generation request. + public partial class ImageGenerationContentFilterResults + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ImageGenerationContentFilterResults() + { + } + + /// Initializes a new instance of . + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Keeps track of any properties unknown to the library. + internal ImageGenerationContentFilterResults(ContentFilterResult sexual, ContentFilterResult violence, ContentFilterResult hate, ContentFilterResult selfHarm, IDictionary serializedAdditionalRawData) + { + Sexual = sexual; + Violence = violence; + Hate = hate; + SelfHarm = selfHarm; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + public ContentFilterResult Sexual { get; } + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + public ContentFilterResult Violence { get; } + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + public ContentFilterResult Hate { get; } + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + public ContentFilterResult SelfHarm { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.Serialization.cs new file mode 100644 index 000000000000..039a7e59aa06 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.Serialization.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ImageGenerationData : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ImageGenerationData)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(Url)) + { + writer.WritePropertyName("url"u8); + writer.WriteStringValue(Url.AbsoluteUri); + } + if (Optional.IsDefined(Base64Data)) + { + writer.WritePropertyName("b64_json"u8); + writer.WriteStringValue(Base64Data); + } + if (Optional.IsDefined(ContentFilterResults)) + { + writer.WritePropertyName("content_filter_results"u8); + writer.WriteObjectValue(ContentFilterResults, options); + } + if (Optional.IsDefined(RevisedPrompt)) + { + writer.WritePropertyName("revised_prompt"u8); + writer.WriteStringValue(RevisedPrompt); + } + if (Optional.IsDefined(PromptFilterResults)) + { + writer.WritePropertyName("prompt_filter_results"u8); + writer.WriteObjectValue(PromptFilterResults, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ImageGenerationData 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(ImageGenerationData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeImageGenerationData(document.RootElement, options); + } + + internal static ImageGenerationData DeserializeImageGenerationData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Uri url = default; + string b64Json = default; + ImageGenerationContentFilterResults contentFilterResults = default; + string revisedPrompt = default; + ImageGenerationPromptFilterResults promptFilterResults = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("url"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + url = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("b64_json"u8)) + { + b64Json = property.Value.GetString(); + continue; + } + if (property.NameEquals("content_filter_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + contentFilterResults = ImageGenerationContentFilterResults.DeserializeImageGenerationContentFilterResults(property.Value, options); + continue; + } + if (property.NameEquals("revised_prompt"u8)) + { + revisedPrompt = property.Value.GetString(); + continue; + } + if (property.NameEquals("prompt_filter_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + promptFilterResults = ImageGenerationPromptFilterResults.DeserializeImageGenerationPromptFilterResults(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ImageGenerationData( + url, + b64Json, + contentFilterResults, + revisedPrompt, + promptFilterResults, + serializedAdditionalRawData); + } + + 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(ImageGenerationData)} does not support writing '{options.Format}' format."); + } + } + + ImageGenerationData 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 DeserializeImageGenerationData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ImageGenerationData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ImageGenerationData FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeImageGenerationData(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.cs new file mode 100644 index 000000000000..63091f309bba --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A representation of a single generated image, provided as either base64-encoded data or as a URL from which the image + /// may be retrieved. + /// + public partial class ImageGenerationData + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ImageGenerationData() + { + } + + /// Initializes a new instance of . + /// The URL that provides temporary access to download the generated image. + /// The complete data for an image, represented as a base64-encoded string. + /// Information about the content filtering results. + /// + /// The final prompt used by the model to generate the image. + /// Only provided with dall-3-models and only when revisions were made to the prompt. + /// + /// + /// Information about the content filtering category (hate, sexual, violence, self_harm), if + /// it has been detected, as well as the severity level (very_low, low, medium, high-scale + /// that determines the intensity and risk level of harmful content) and if it has been + /// filtered or not. Information about jailbreak content and profanity, if it has been detected, + /// and if it has been filtered or not. And information about customer block list, if it has + /// been filtered and its id. + /// + /// Keeps track of any properties unknown to the library. + internal ImageGenerationData(Uri url, string base64Data, ImageGenerationContentFilterResults contentFilterResults, string revisedPrompt, ImageGenerationPromptFilterResults promptFilterResults, IDictionary serializedAdditionalRawData) + { + Url = url; + Base64Data = base64Data; + ContentFilterResults = contentFilterResults; + RevisedPrompt = revisedPrompt; + PromptFilterResults = promptFilterResults; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The URL that provides temporary access to download the generated image. + public Uri Url { get; } + /// The complete data for an image, represented as a base64-encoded string. + public string Base64Data { get; } + /// Information about the content filtering results. + public ImageGenerationContentFilterResults ContentFilterResults { get; } + /// + /// The final prompt used by the model to generate the image. + /// Only provided with dall-3-models and only when revisions were made to the prompt. + /// + public string RevisedPrompt { get; } + /// + /// Information about the content filtering category (hate, sexual, violence, self_harm), if + /// it has been detected, as well as the severity level (very_low, low, medium, high-scale + /// that determines the intensity and risk level of harmful content) and if it has been + /// filtered or not. Information about jailbreak content and profanity, if it has been detected, + /// and if it has been filtered or not. And information about customer block list, if it has + /// been filtered and its id. + /// + public ImageGenerationPromptFilterResults PromptFilterResults { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.Serialization.cs new file mode 100644 index 000000000000..528a86636d2d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.Serialization.cs @@ -0,0 +1,241 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ImageGenerationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ImageGenerationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + writer.WritePropertyName("prompt"u8); + writer.WriteStringValue(Prompt); + if (Optional.IsDefined(ImageCount)) + { + writer.WritePropertyName("n"u8); + writer.WriteNumberValue(ImageCount.Value); + } + if (Optional.IsDefined(Size)) + { + writer.WritePropertyName("size"u8); + writer.WriteStringValue(Size.Value.ToString()); + } + if (Optional.IsDefined(ResponseFormat)) + { + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); + } + if (Optional.IsDefined(Quality)) + { + writer.WritePropertyName("quality"u8); + writer.WriteStringValue(Quality.Value.ToString()); + } + if (Optional.IsDefined(Style)) + { + writer.WritePropertyName("style"u8); + writer.WriteStringValue(Style.Value.ToString()); + } + if (Optional.IsDefined(User)) + { + writer.WritePropertyName("user"u8); + writer.WriteStringValue(User); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ImageGenerationOptions 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(ImageGenerationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeImageGenerationOptions(document.RootElement, options); + } + + internal static ImageGenerationOptions DeserializeImageGenerationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string model = default; + string prompt = default; + int? n = default; + ImageSize? size = default; + ImageGenerationResponseFormat? responseFormat = default; + ImageGenerationQuality? quality = default; + ImageGenerationStyle? style = default; + string user = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (property.NameEquals("prompt"u8)) + { + prompt = property.Value.GetString(); + continue; + } + if (property.NameEquals("n"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + n = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("size"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + size = new ImageSize(property.Value.GetString()); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = new ImageGenerationResponseFormat(property.Value.GetString()); + continue; + } + if (property.NameEquals("quality"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + quality = new ImageGenerationQuality(property.Value.GetString()); + continue; + } + if (property.NameEquals("style"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + style = new ImageGenerationStyle(property.Value.GetString()); + continue; + } + if (property.NameEquals("user"u8)) + { + user = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ImageGenerationOptions( + model, + prompt, + n, + size, + responseFormat, + quality, + style, + user, + serializedAdditionalRawData); + } + + 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(ImageGenerationOptions)} does not support writing '{options.Format}' format."); + } + } + + ImageGenerationOptions 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 DeserializeImageGenerationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ImageGenerationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ImageGenerationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeImageGenerationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.cs new file mode 100644 index 000000000000..d5756901ef45 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Represents the request data used to generate images. + public partial class ImageGenerationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A description of the desired images. + /// is null. + public ImageGenerationOptions(string prompt) + { + Argument.AssertNotNull(prompt, nameof(prompt)); + + Prompt = prompt; + } + + /// Initializes a new instance of . + /// + /// The model name or Azure OpenAI model deployment name to use for image generation. If not specified, dall-e-2 will be + /// inferred as a default. + /// + /// A description of the desired images. + /// + /// The number of images to generate. + /// Dall-e-2 models support values between 1 and 10. + /// Dall-e-3 models only support a value of 1. + /// + /// + /// The desired dimensions for generated images. + /// Dall-e-2 models support 256x256, 512x512, or 1024x1024. + /// Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. + /// + /// The format in which image generation response items should be presented. + /// + /// The desired image generation quality level to use. + /// Only configurable with dall-e-3 models. + /// + /// + /// The desired image generation style to use. + /// Only configurable with dall-e-3 models. + /// + /// A unique identifier representing your end-user, which can help to monitor and detect abuse. + /// Keeps track of any properties unknown to the library. + internal ImageGenerationOptions(string deploymentName, string prompt, int? imageCount, ImageSize? size, ImageGenerationResponseFormat? responseFormat, ImageGenerationQuality? quality, ImageGenerationStyle? style, string user, IDictionary serializedAdditionalRawData) + { + DeploymentName = deploymentName; + Prompt = prompt; + ImageCount = imageCount; + Size = size; + ResponseFormat = responseFormat; + Quality = quality; + Style = style; + User = user; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ImageGenerationOptions() + { + } + + /// + /// The model name or Azure OpenAI model deployment name to use for image generation. If not specified, dall-e-2 will be + /// inferred as a default. + /// + public string DeploymentName { get; set; } + /// A description of the desired images. + public string Prompt { get; set; } + /// + /// The number of images to generate. + /// Dall-e-2 models support values between 1 and 10. + /// Dall-e-3 models only support a value of 1. + /// + public int? ImageCount { get; set; } + /// + /// The desired dimensions for generated images. + /// Dall-e-2 models support 256x256, 512x512, or 1024x1024. + /// Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. + /// + public ImageSize? Size { get; set; } + /// The format in which image generation response items should be presented. + public ImageGenerationResponseFormat? ResponseFormat { get; set; } + /// + /// The desired image generation quality level to use. + /// Only configurable with dall-e-3 models. + /// + public ImageGenerationQuality? Quality { get; set; } + /// + /// The desired image generation style to use. + /// Only configurable with dall-e-3 models. + /// + public ImageGenerationStyle? Style { get; set; } + /// A unique identifier representing your end-user, which can help to monitor and detect abuse. + public string User { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/RequestImageContentFilterResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.Serialization.cs similarity index 57% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/RequestImageContentFilterResult.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.Serialization.cs index 150a5f9d7775..2bb2794da06b 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/RequestImageContentFilterResult.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.Serialization.cs @@ -1,69 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; namespace Azure.AI.OpenAI { - public partial class RequestImageContentFilterResult : IJsonModel + public partial class ImageGenerationPromptFilterResults : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(RequestImageContentFilterResult)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationPromptFilterResults)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("profanity") != true && Optional.IsDefined(Profanity)) - { - writer.WritePropertyName("profanity"u8); - writer.WriteObjectValue(Profanity, options); - } - if (SerializedAdditionalRawData?.ContainsKey("custom_blocklists") != true && Optional.IsDefined(CustomBlocklists)) - { - writer.WritePropertyName("custom_blocklists"u8); - writer.WriteObjectValue(CustomBlocklists, options); - } - if (SerializedAdditionalRawData?.ContainsKey("jailbreak") != true) - { - writer.WritePropertyName("jailbreak"u8); - writer.WriteObjectValue(Jailbreak, options); - } - if (SerializedAdditionalRawData?.ContainsKey("sexual") != true && Optional.IsDefined(Sexual)) + if (Optional.IsDefined(Sexual)) { writer.WritePropertyName("sexual"u8); writer.WriteObjectValue(Sexual, options); } - if (SerializedAdditionalRawData?.ContainsKey("violence") != true && Optional.IsDefined(Violence)) + if (Optional.IsDefined(Violence)) { writer.WritePropertyName("violence"u8); writer.WriteObjectValue(Violence, options); } - if (SerializedAdditionalRawData?.ContainsKey("hate") != true && Optional.IsDefined(Hate)) + if (Optional.IsDefined(Hate)) { writer.WritePropertyName("hate"u8); writer.WriteObjectValue(Hate, options); } - if (SerializedAdditionalRawData?.ContainsKey("self_harm") != true && Optional.IsDefined(SelfHarm)) + if (Optional.IsDefined(SelfHarm)) { writer.WritePropertyName("self_harm"u8); writer.WriteObjectValue(SelfHarm, options); } - if (SerializedAdditionalRawData != null) + if (Optional.IsDefined(Profanity)) + { + writer.WritePropertyName("profanity"u8); + writer.WriteObjectValue(Profanity, options); + } + if (Optional.IsDefined(Jailbreak)) + { + writer.WritePropertyName("jailbreak"u8); + writer.WriteObjectValue(Jailbreak, options); + } + if (Optional.IsDefined(CustomBlocklists)) + { + writer.WritePropertyName("custom_blocklists"u8); + writer.WriteObjectValue(CustomBlocklists, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -78,19 +79,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, Mo writer.WriteEndObject(); } - RequestImageContentFilterResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ImageGenerationPromptFilterResults 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(RequestImageContentFilterResult)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationPromptFilterResults)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeRequestImageContentFilterResult(document.RootElement, options); + return DeserializeImageGenerationPromptFilterResults(document.RootElement, options); } - internal static RequestImageContentFilterResult DeserializeRequestImageContentFilterResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static ImageGenerationPromptFilterResults DeserializeImageGenerationPromptFilterResults(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -98,137 +99,142 @@ internal static RequestImageContentFilterResult DeserializeRequestImageContentFi { return null; } + ContentFilterResult sexual = default; + ContentFilterResult violence = default; + ContentFilterResult hate = default; + ContentFilterResult selfHarm = default; ContentFilterDetectionResult profanity = default; - ContentFilterBlocklistResult customBlocklists = default; ContentFilterDetectionResult jailbreak = default; - ContentFilterSeverityResult sexual = default; - ContentFilterSeverityResult violence = default; - ContentFilterSeverityResult hate = default; - ContentFilterSeverityResult selfHarm = default; + ContentFilterDetailedResults customBlocklists = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("profanity"u8)) + if (property.NameEquals("sexual"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - profanity = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); + sexual = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } - if (property.NameEquals("custom_blocklists"u8)) + if (property.NameEquals("violence"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - customBlocklists = ContentFilterBlocklistResult.DeserializeContentFilterBlocklistResult(property.Value, options); + violence = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } - if (property.NameEquals("jailbreak"u8)) + if (property.NameEquals("hate"u8)) { - jailbreak = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + hate = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } - if (property.NameEquals("sexual"u8)) + if (property.NameEquals("self_harm"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - sexual = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + selfHarm = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); continue; } - if (property.NameEquals("violence"u8)) + if (property.NameEquals("profanity"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - violence = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + profanity = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); continue; } - if (property.NameEquals("hate"u8)) + if (property.NameEquals("jailbreak"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - hate = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + jailbreak = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); continue; } - if (property.NameEquals("self_harm"u8)) + if (property.NameEquals("custom_blocklists"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - selfHarm = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(property.Value, options); + customBlocklists = ContentFilterDetailedResults.DeserializeContentFilterDetailedResults(property.Value, options); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new RequestImageContentFilterResult( + return new ImageGenerationPromptFilterResults( sexual, violence, hate, selfHarm, - serializedAdditionalRawData, profanity, + jailbreak, customBlocklists, - jailbreak); + 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(RequestImageContentFilterResult)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationPromptFilterResults)} does not support writing '{options.Format}' format."); } } - RequestImageContentFilterResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ImageGenerationPromptFilterResults 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 DeserializeRequestImageContentFilterResult(document.RootElement, options); + return DeserializeImageGenerationPromptFilterResults(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(RequestImageContentFilterResult)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationPromptFilterResults)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new RequestImageContentFilterResult FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static ImageGenerationPromptFilterResults FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeRequestImageContentFilterResult(document.RootElement); + return DeserializeImageGenerationPromptFilterResults(document.RootElement); } - /// Convert into a . - internal override BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.cs new file mode 100644 index 000000000000..e66c52bc7c1f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Describes the content filtering results for the prompt of a image generation request. + public partial class ImageGenerationPromptFilterResults + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ImageGenerationPromptFilterResults() + { + } + + /// Initializes a new instance of . + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Whether a jailbreak attempt was detected in the prompt. + /// Information about customer block lists and if something was detected the associated list ID. + /// Keeps track of any properties unknown to the library. + internal ImageGenerationPromptFilterResults(ContentFilterResult sexual, ContentFilterResult violence, ContentFilterResult hate, ContentFilterResult selfHarm, ContentFilterDetectionResult profanity, ContentFilterDetectionResult jailbreak, ContentFilterDetailedResults customBlocklists, IDictionary serializedAdditionalRawData) + { + Sexual = sexual; + Violence = violence; + Hate = hate; + SelfHarm = selfHarm; + Profanity = profanity; + Jailbreak = jailbreak; + CustomBlocklists = customBlocklists; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// Describes language related to anatomical organs and genitals, romantic relationships, + /// acts portrayed in erotic or affectionate terms, physical sexual acts, including + /// those portrayed as an assault or a forced sexual violent act against one’s will, + /// prostitution, pornography, and abuse. + /// + public ContentFilterResult Sexual { get; } + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + public ContentFilterResult Violence { get; } + /// + /// Describes language attacks or uses that include pejorative or discriminatory language + /// with reference to a person or identity group on the basis of certain differentiating + /// attributes of these groups including but not limited to race, ethnicity, nationality, + /// gender identity and expression, sexual orientation, religion, immigration status, ability + /// status, personal appearance, and body size. + /// + public ContentFilterResult Hate { get; } + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + public ContentFilterResult SelfHarm { get; } + /// Describes whether profanity was detected. + public ContentFilterDetectionResult Profanity { get; } + /// Whether a jailbreak attempt was detected in the prompt. + public ContentFilterDetectionResult Jailbreak { get; } + /// Information about customer block lists and if something was detected the associated list ID. + public ContentFilterDetailedResults CustomBlocklists { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationQuality.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationQuality.cs new file mode 100644 index 000000000000..31d282d1a6db --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationQuality.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// + /// An image generation configuration that specifies how the model should prioritize quality, cost, and speed. + /// Only configurable with dall-e-3 models. + /// + public readonly partial struct ImageGenerationQuality : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ImageGenerationQuality(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string StandardValue = "standard"; + private const string HdValue = "hd"; + + /// Requests image generation with standard, balanced characteristics of quality, cost, and speed. + public static ImageGenerationQuality Standard { get; } = new ImageGenerationQuality(StandardValue); + /// Requests image generation with higher quality, higher cost and lower speed relative to standard. + public static ImageGenerationQuality Hd { get; } = new ImageGenerationQuality(HdValue); + /// Determines if two values are the same. + public static bool operator ==(ImageGenerationQuality left, ImageGenerationQuality right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ImageGenerationQuality left, ImageGenerationQuality right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ImageGenerationQuality(string value) => new ImageGenerationQuality(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ImageGenerationQuality other && Equals(other); + /// + public bool Equals(ImageGenerationQuality other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationResponseFormat.cs new file mode 100644 index 000000000000..b4445f444a22 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationResponseFormat.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The format in which the generated images are returned. + internal readonly partial struct ImageGenerationResponseFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ImageGenerationResponseFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UrlValue = "url"; + private const string Base64Value = "b64_json"; + + /// Image generation response items should provide a URL from which the image may be retrieved. + public static ImageGenerationResponseFormat Url { get; } = new ImageGenerationResponseFormat(UrlValue); + /// Image generation response items should provide image data as a base64-encoded string. + public static ImageGenerationResponseFormat Base64 { get; } = new ImageGenerationResponseFormat(Base64Value); + /// Determines if two values are the same. + public static bool operator ==(ImageGenerationResponseFormat left, ImageGenerationResponseFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ImageGenerationResponseFormat left, ImageGenerationResponseFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ImageGenerationResponseFormat(string value) => new ImageGenerationResponseFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ImageGenerationResponseFormat other && Equals(other); + /// + public bool Equals(ImageGenerationResponseFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationStyle.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationStyle.cs new file mode 100644 index 000000000000..800d3ae8e5bf --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationStyle.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// + /// An image generation configuration that specifies how the model should incorporate realism and other visual characteristics. + /// Only configurable with dall-e-3 models. + /// + public readonly partial struct ImageGenerationStyle : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ImageGenerationStyle(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NaturalValue = "natural"; + private const string VividValue = "vivid"; + + /// Requests image generation in a natural style with less preference for dramatic and hyper-realistic characteristics. + public static ImageGenerationStyle Natural { get; } = new ImageGenerationStyle(NaturalValue); + /// + /// Requests image generation in a vivid style with a higher preference for dramatic and hyper-realistic + /// characteristics. + /// + public static ImageGenerationStyle Vivid { get; } = new ImageGenerationStyle(VividValue); + /// Determines if two values are the same. + public static bool operator ==(ImageGenerationStyle left, ImageGenerationStyle right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ImageGenerationStyle left, ImageGenerationStyle right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ImageGenerationStyle(string value) => new ImageGenerationStyle(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ImageGenerationStyle other && Equals(other); + /// + public bool Equals(ImageGenerationStyle other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.Serialization.cs new file mode 100644 index 000000000000..aaf4621d6b1b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ImageGenerations : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ImageGenerations)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("created"u8); + writer.WriteNumberValue(Created, "U"); + writer.WritePropertyName("data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ImageGenerations 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(ImageGenerations)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeImageGenerations(document.RootElement, options); + } + + internal static ImageGenerations DeserializeImageGenerations(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + DateTimeOffset created = default; + IReadOnlyList data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("created"u8)) + { + created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("data"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ImageGenerationData.DeserializeImageGenerationData(item, options)); + } + data = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ImageGenerations(created, data, serializedAdditionalRawData); + } + + 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(ImageGenerations)} does not support writing '{options.Format}' format."); + } + } + + ImageGenerations 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 DeserializeImageGenerations(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ImageGenerations)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ImageGenerations FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeImageGenerations(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.cs new file mode 100644 index 000000000000..66823f093e60 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The result of a successful image generation operation. + public partial class ImageGenerations + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// A timestamp representing when this operation was started. + /// Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. + /// + /// The images generated by the operation. + /// is null. + internal ImageGenerations(DateTimeOffset created, IEnumerable data) + { + Argument.AssertNotNull(data, nameof(data)); + + Created = created; + Data = data.ToList(); + } + + /// Initializes a new instance of . + /// + /// A timestamp representing when this operation was started. + /// Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. + /// + /// The images generated by the operation. + /// Keeps track of any properties unknown to the library. + internal ImageGenerations(DateTimeOffset created, IReadOnlyList data, IDictionary serializedAdditionalRawData) + { + Created = created; + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ImageGenerations() + { + } + + /// + /// A timestamp representing when this operation was started. + /// Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. + /// + public DateTimeOffset Created { get; } + /// The images generated by the operation. + public IReadOnlyList Data { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageSize.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageSize.cs new file mode 100644 index 000000000000..46b72f092ac6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageSize.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The desired size of generated images. + public readonly partial struct ImageSize : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ImageSize(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string Size256x256Value = "256x256"; + private const string Size512x512Value = "512x512"; + private const string Size1024x1024Value = "1024x1024"; + private const string Size1792x1024Value = "1792x1024"; + private const string Size1024x1792Value = "1024x1792"; + + /// + /// Very small image size of 256x256 pixels. + /// Only supported with dall-e-2 models. + /// + public static ImageSize Size256x256 { get; } = new ImageSize(Size256x256Value); + /// + /// A smaller image size of 512x512 pixels. + /// Only supported with dall-e-2 models. + /// + public static ImageSize Size512x512 { get; } = new ImageSize(Size512x512Value); + /// + /// A standard, square image size of 1024x1024 pixels. + /// Supported by both dall-e-2 and dall-e-3 models. + /// + public static ImageSize Size1024x1024 { get; } = new ImageSize(Size1024x1024Value); + /// + /// A wider image size of 1024x1792 pixels. + /// Only supported with dall-e-3 models. + /// + public static ImageSize Size1792x1024 { get; } = new ImageSize(Size1792x1024Value); + /// + /// A taller image size of 1792x1024 pixels. + /// Only supported with dall-e-3 models. + /// + public static ImageSize Size1024x1792 { get; } = new ImageSize(Size1024x1792Value); + /// Determines if two values are the same. + public static bool operator ==(ImageSize left, ImageSize right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ImageSize left, ImageSize right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ImageSize(string value) => new ImageSize(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ImageSize other && Equals(other); + /// + public bool Equals(ImageSize other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Argument.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Argument.cs index 5a8ab138b061..21077f384b16 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Argument.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Argument.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/BinaryContentHelper.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/BinaryContentHelper.cs deleted file mode 100644 index 94ae48ee4fd1..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/BinaryContentHelper.cs +++ /dev/null @@ -1,133 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal static class BinaryContentHelper - { - public static BinaryContent FromEnumerable(IEnumerable enumerable) - where T : notnull - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteStartArray(); - foreach (var item in enumerable) - { - content.JsonWriter.WriteObjectValue(item, ModelSerializationExtensions.WireOptions); - } - content.JsonWriter.WriteEndArray(); - - return content; - } - - public static BinaryContent FromEnumerable(IEnumerable enumerable) - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteStartArray(); - foreach (var item in enumerable) - { - if (item == null) - { - content.JsonWriter.WriteNullValue(); - } - else - { -#if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item); -#else - using (JsonDocument document = JsonDocument.Parse(item)) - { - JsonSerializer.Serialize(content.JsonWriter, document.RootElement); - } -#endif - } - } - content.JsonWriter.WriteEndArray(); - - return content; - } - - public static BinaryContent FromEnumerable(ReadOnlySpan span) - where T : notnull - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteStartArray(); - for (int i = 0; i < span.Length; i++) - { - content.JsonWriter.WriteObjectValue(span[i], ModelSerializationExtensions.WireOptions); - } - content.JsonWriter.WriteEndArray(); - - return content; - } - - public static BinaryContent FromDictionary(IDictionary dictionary) - where TValue : notnull - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteStartObject(); - foreach (var item in dictionary) - { - content.JsonWriter.WritePropertyName(item.Key); - content.JsonWriter.WriteObjectValue(item.Value, ModelSerializationExtensions.WireOptions); - } - content.JsonWriter.WriteEndObject(); - - return content; - } - - public static BinaryContent FromDictionary(IDictionary dictionary) - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteStartObject(); - foreach (var item in dictionary) - { - content.JsonWriter.WritePropertyName(item.Key); - if (item.Value == null) - { - content.JsonWriter.WriteNullValue(); - } - else - { -#if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(content.JsonWriter, document.RootElement); - } -#endif - } - } - content.JsonWriter.WriteEndObject(); - - return content; - } - - public static BinaryContent FromObject(object value) - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); - content.JsonWriter.WriteObjectValue(value, ModelSerializationExtensions.WireOptions); - return content; - } - - public static BinaryContent FromObject(BinaryData value) - { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); -#if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(value); -#else - using (JsonDocument document = JsonDocument.Parse(value)) - { - JsonSerializer.Serialize(content.JsonWriter, document.RootElement); - } -#endif - return content; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingDictionary.cs index 058e71abee85..8bd92c447cd8 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingDictionary.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingList.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingList.cs index 9c6986a3ad4a..b06e0a43ffe7 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingList.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingList.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientPipelineExtensions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientPipelineExtensions.cs deleted file mode 100644 index e1d028882494..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientPipelineExtensions.cs +++ /dev/null @@ -1,41 +0,0 @@ -// - -#nullable disable - -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Threading.Tasks; - -namespace Azure.AI.OpenAI -{ - internal static partial class ClientPipelineExtensions - { - public static async ValueTask> ProcessHeadAsBoolMessageAsync(this ClientPipeline pipeline, PipelineMessage message, RequestOptions options) - { - PipelineResponse response = await pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); - switch (response.Status) - { - case >= 200 and < 300: - return ClientResult.FromValue(true, response); - case >= 400 and < 500: - return ClientResult.FromValue(false, response); - default: - return new ErrorResult(response, new ClientResultException(response)); - } - } - - public static ClientResult ProcessHeadAsBoolMessage(this ClientPipeline pipeline, PipelineMessage message, RequestOptions options) - { - PipelineResponse response = pipeline.ProcessMessage(message, options); - switch (response.Status) - { - case >= 200 and < 300: - return ClientResult.FromValue(true, response); - case >= 400 and < 500: - return ClientResult.FromValue(false, response); - default: - return new ErrorResult(response, new ClientResultException(response)); - } - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientUriBuilder.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientUriBuilder.cs deleted file mode 100644 index aa2ae4da331e..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientUriBuilder.cs +++ /dev/null @@ -1,190 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Azure.AI.OpenAI -{ - internal partial class ClientUriBuilder - { - private UriBuilder _uriBuilder; - private StringBuilder _pathBuilder; - private StringBuilder _queryBuilder; - - public ClientUriBuilder() - { - } - - private UriBuilder UriBuilder => _uriBuilder ??= new UriBuilder(); - - private StringBuilder PathBuilder => _pathBuilder ??= new StringBuilder(UriBuilder.Path); - - private StringBuilder QueryBuilder => _queryBuilder ??= new StringBuilder(UriBuilder.Query); - - public void Reset(Uri uri) - { - _uriBuilder = new UriBuilder(uri); - _pathBuilder = new StringBuilder(UriBuilder.Path); - _queryBuilder = new StringBuilder(UriBuilder.Query); - } - - public void AppendPath(string value, bool escape) - { - Argument.AssertNotNullOrWhiteSpace(value, nameof(value)); - - if (escape) - { - value = Uri.EscapeDataString(value); - } - - if (PathBuilder.Length > 0 && PathBuilder[PathBuilder.Length - 1] == '/' && value[0] == '/') - { - PathBuilder.Remove(PathBuilder.Length - 1, 1); - } - - PathBuilder.Append(value); - UriBuilder.Path = PathBuilder.ToString(); - } - - public void AppendPath(bool value, bool escape = false) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendPath(float value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendPath(double value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendPath(int value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendPath(byte[] value, string format, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } - - public void AppendPath(IEnumerable value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendPath(DateTimeOffset value, string format, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } - - public void AppendPath(TimeSpan value, string format, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } - - public void AppendPath(Guid value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendPath(long value, bool escape = true) - { - AppendPath(ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendQuery(string name, string value, bool escape) - { - Argument.AssertNotNullOrWhiteSpace(name, nameof(name)); - Argument.AssertNotNullOrWhiteSpace(value, nameof(value)); - - if (QueryBuilder.Length > 0) - { - QueryBuilder.Append('&'); - } - - if (escape) - { - value = Uri.EscapeDataString(value); - } - - QueryBuilder.Append(name); - QueryBuilder.Append('='); - QueryBuilder.Append(value); - } - - public void AppendQuery(string name, bool value, bool escape = false) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendQuery(string name, float value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendQuery(string name, DateTimeOffset value, string format, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } - - public void AppendQuery(string name, TimeSpan value, string format, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } - - public void AppendQuery(string name, double value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendQuery(string name, decimal value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendQuery(string name, int value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendQuery(string name, long value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendQuery(string name, TimeSpan value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendQuery(string name, byte[] value, string format, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value, format), escape); - } - - public void AppendQuery(string name, Guid value, bool escape = true) - { - AppendQuery(name, ModelSerializationExtensions.TypeFormatters.ConvertToString(value), escape); - } - - public void AppendQueryDelimited(string name, IEnumerable value, string delimiter, bool escape = true) - { - var stringValues = value.Select(v => ModelSerializationExtensions.TypeFormatters.ConvertToString(v)); - AppendQuery(name, string.Join(delimiter, stringValues), escape); - } - - public void AppendQueryDelimited(string name, IEnumerable value, string delimiter, string format, bool escape = true) - { - var stringValues = value.Select(v => ModelSerializationExtensions.TypeFormatters.ConvertToString(v, format)); - AppendQuery(name, string.Join(delimiter, stringValues), escape); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ErrorResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ErrorResult.cs deleted file mode 100644 index f9ea3276e769..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ErrorResult.cs +++ /dev/null @@ -1,23 +0,0 @@ -// - -#nullable disable - -using System.ClientModel; -using System.ClientModel.Primitives; - -namespace Azure.AI.OpenAI -{ - internal class ErrorResult : ClientResult - { - private readonly PipelineResponse _response; - private readonly ClientResultException _exception; - - public ErrorResult(PipelineResponse response, ClientResultException exception) : base(default, response) - { - _response = response; - _exception = exception; - } - - public override T Value => throw _exception; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ModelSerializationExtensions.cs index f4286bb0eeca..4a45f613de8c 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ModelSerializationExtensions.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ModelSerializationExtensions.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -9,13 +12,13 @@ using System.Globalization; using System.Text.Json; using System.Xml; +using Azure.Core; namespace Azure.AI.OpenAI { internal static class ModelSerializationExtensions { internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); - internal static readonly BinaryData SentinelValue = BinaryData.FromObjectAsJson("__EMPTY__"); public static object GetObject(this JsonElement element) { @@ -174,6 +177,9 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, T value, Mode case IJsonModel jsonModel: jsonModel.Write(writer, options ?? WireOptions); break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; case byte[] bytes: writer.WriteBase64StringValue(bytes); break; @@ -250,13 +256,6 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, object value, Mo writer.WriteObjectValue(value, options); } - internal static bool IsSentinelValue(BinaryData value) - { - ReadOnlySpan sentinelSpan = SentinelValue.ToMemory().Span; - ReadOnlySpan valueSpan = value.ToMemory().Span; - return sentinelSpan.SequenceEqual(valueSpan); - } - internal static class TypeFormatters { private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; @@ -267,7 +266,7 @@ internal static class TypeFormatters public static string ToString(DateTime value, string format) => value.Kind switch { DateTimeKind.Utc => ToString((DateTimeOffset)value, format), - _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Generated clients require it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") }; public static string ToString(DateTimeOffset value, string format) => format switch diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/MultipartFormDataBinaryContent.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/MultipartFormDataRequestContent.cs similarity index 92% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/MultipartFormDataBinaryContent.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/MultipartFormDataRequestContent.cs index 43825f6b4a86..68d9091c6708 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/MultipartFormDataBinaryContent.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/MultipartFormDataRequestContent.cs @@ -1,27 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.Globalization; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; namespace Azure.AI.OpenAI { - internal class MultipartFormDataBinaryContent : BinaryContent + internal class MultipartFormDataRequestContent : RequestContent { - private readonly MultipartFormDataContent _multipartContent; + private readonly System.Net.Http.MultipartFormDataContent _multipartContent; private static readonly Random _random = new Random(); private static readonly char[] _boundaryValues = "0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".ToCharArray(); - public MultipartFormDataBinaryContent() + public MultipartFormDataRequestContent() { - _multipartContent = new MultipartFormDataContent(CreateBoundary()); + _multipartContent = new System.Net.Http.MultipartFormDataContent(CreateBoundary()); } public string ContentType @@ -176,7 +180,9 @@ public override void WriteTo(Stream stream, CancellationToken cancellationToken #if NET6_0_OR_GREATER _multipartContent.CopyTo(stream, default, cancellationToken); #else - _multipartContent.CopyToAsync(stream).GetAwaiter().GetResult(); +#pragma warning disable AZC0107 + _multipartContent.CopyToAsync(stream).EnsureCompleted(); +#pragma warning restore AZC0107 #endif } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Optional.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Optional.cs index 56bba5f656ac..a58dc86ec6a1 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Optional.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Optional.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonBinaryContent.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonRequestContent.cs similarity index 82% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonBinaryContent.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonRequestContent.cs index 7f70307bf7f8..62b7404a506e 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonBinaryContent.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -1,21 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable -using System.ClientModel; using System.IO; using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Azure.Core; namespace Azure.AI.OpenAI { - internal class Utf8JsonBinaryContent : BinaryContent + internal class Utf8JsonRequestContent : RequestContent { private readonly MemoryStream _stream; - private readonly BinaryContent _content; + private readonly RequestContent _content; - public Utf8JsonBinaryContent() + public Utf8JsonRequestContent() { _stream = new MemoryStream(); _content = Create(_stream); diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.Serialization.cs deleted file mode 100644 index 344aed0274a7..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceAccessTokenAuthenticationOptions : 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(InternalAzureChatDataSourceAccessTokenAuthenticationOptions)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("access_token") != true) - { - writer.WritePropertyName("access_token"u8); - writer.WriteStringValue(AccessToken); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceAccessTokenAuthenticationOptions 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(InternalAzureChatDataSourceAccessTokenAuthenticationOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceAccessTokenAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceAccessTokenAuthenticationOptions DeserializeInternalAzureChatDataSourceAccessTokenAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string accessToken = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("access_token"u8)) - { - accessToken = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceAccessTokenAuthenticationOptions(type, serializedAdditionalRawData, accessToken); - } - - 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(InternalAzureChatDataSourceAccessTokenAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceAccessTokenAuthenticationOptions 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 DeserializeInternalAzureChatDataSourceAccessTokenAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceAccessTokenAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceAccessTokenAuthenticationOptions FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceAccessTokenAuthenticationOptions(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.cs deleted file mode 100644 index 73fc1546e469..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.cs +++ /dev/null @@ -1,42 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureChatDataSourceAccessTokenAuthenticationOptions. - internal partial class InternalAzureChatDataSourceAccessTokenAuthenticationOptions : DataSourceAuthentication - { - /// Initializes a new instance of . - /// - /// is null. - public InternalAzureChatDataSourceAccessTokenAuthenticationOptions(string accessToken) - { - Argument.AssertNotNull(accessToken, nameof(accessToken)); - - Type = "access_token"; - AccessToken = accessToken; - } - - /// Initializes a new instance of . - /// Discriminator. - /// Keeps track of any properties unknown to the library. - /// - internal InternalAzureChatDataSourceAccessTokenAuthenticationOptions(string type, IDictionary serializedAdditionalRawData, string accessToken) : base(type, serializedAdditionalRawData) - { - AccessToken = accessToken; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureChatDataSourceAccessTokenAuthenticationOptions() - { - } - - /// Gets the access token. - internal string AccessToken { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceApiKeyAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceApiKeyAuthenticationOptions.cs deleted file mode 100644 index 1d92c00c05f7..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceApiKeyAuthenticationOptions.cs +++ /dev/null @@ -1,42 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureChatDataSourceApiKeyAuthenticationOptions. - internal partial class InternalAzureChatDataSourceApiKeyAuthenticationOptions : DataSourceAuthentication - { - /// Initializes a new instance of . - /// - /// is null. - public InternalAzureChatDataSourceApiKeyAuthenticationOptions(string key) - { - Argument.AssertNotNull(key, nameof(key)); - - Type = "api_key"; - Key = key; - } - - /// Initializes a new instance of . - /// Discriminator. - /// Keeps track of any properties unknown to the library. - /// - internal InternalAzureChatDataSourceApiKeyAuthenticationOptions(string type, IDictionary serializedAdditionalRawData, string key) : base(type, serializedAdditionalRawData) - { - Key = key; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureChatDataSourceApiKeyAuthenticationOptions() - { - } - - /// Gets the key. - internal string Key { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.Serialization.cs deleted file mode 100644 index 87563d7c14b9..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceConnectionStringAuthenticationOptions : 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(InternalAzureChatDataSourceConnectionStringAuthenticationOptions)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("connection_string") != true) - { - writer.WritePropertyName("connection_string"u8); - writer.WriteStringValue(ConnectionString); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceConnectionStringAuthenticationOptions 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(InternalAzureChatDataSourceConnectionStringAuthenticationOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceConnectionStringAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceConnectionStringAuthenticationOptions DeserializeInternalAzureChatDataSourceConnectionStringAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string connectionString = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("connection_string"u8)) - { - connectionString = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceConnectionStringAuthenticationOptions(type, serializedAdditionalRawData, connectionString); - } - - 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(InternalAzureChatDataSourceConnectionStringAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceConnectionStringAuthenticationOptions 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 DeserializeInternalAzureChatDataSourceConnectionStringAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceConnectionStringAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceConnectionStringAuthenticationOptions FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceConnectionStringAuthenticationOptions(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.cs deleted file mode 100644 index 86a7f544bd27..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.cs +++ /dev/null @@ -1,42 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureChatDataSourceConnectionStringAuthenticationOptions. - internal partial class InternalAzureChatDataSourceConnectionStringAuthenticationOptions : DataSourceAuthentication - { - /// Initializes a new instance of . - /// - /// is null. - public InternalAzureChatDataSourceConnectionStringAuthenticationOptions(string connectionString) - { - Argument.AssertNotNull(connectionString, nameof(connectionString)); - - Type = "connection_string"; - ConnectionString = connectionString; - } - - /// Initializes a new instance of . - /// Discriminator. - /// Keeps track of any properties unknown to the library. - /// - internal InternalAzureChatDataSourceConnectionStringAuthenticationOptions(string type, IDictionary serializedAdditionalRawData, string connectionString) : base(type, serializedAdditionalRawData) - { - ConnectionString = connectionString; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureChatDataSourceConnectionStringAuthenticationOptions() - { - } - - /// Gets the connection string. - internal string ConnectionString { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceDeploymentNameVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceDeploymentNameVectorizationSource.Serialization.cs deleted file mode 100644 index a322da00a07b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceDeploymentNameVectorizationSource.Serialization.cs +++ /dev/null @@ -1,163 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceDeploymentNameVectorizationSource : 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(InternalAzureChatDataSourceDeploymentNameVectorizationSource)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("deployment_name") != true) - { - writer.WritePropertyName("deployment_name"u8); - writer.WriteStringValue(DeploymentName); - } - if (SerializedAdditionalRawData?.ContainsKey("dimensions") != true && Optional.IsDefined(Dimensions)) - { - writer.WritePropertyName("dimensions"u8); - writer.WriteNumberValue(Dimensions.Value); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceDeploymentNameVectorizationSource 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(InternalAzureChatDataSourceDeploymentNameVectorizationSource)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceDeploymentNameVectorizationSource(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceDeploymentNameVectorizationSource DeserializeInternalAzureChatDataSourceDeploymentNameVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string deploymentName = default; - int? dimensions = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("deployment_name"u8)) - { - deploymentName = property.Value.GetString(); - continue; - } - if (property.NameEquals("dimensions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - dimensions = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceDeploymentNameVectorizationSource(type, serializedAdditionalRawData, deploymentName, dimensions); - } - - 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(InternalAzureChatDataSourceDeploymentNameVectorizationSource)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceDeploymentNameVectorizationSource 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 DeserializeInternalAzureChatDataSourceDeploymentNameVectorizationSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceDeploymentNameVectorizationSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceDeploymentNameVectorizationSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceDeploymentNameVectorizationSource(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceDeploymentNameVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceDeploymentNameVectorizationSource.cs deleted file mode 100644 index e413a85711ef..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceDeploymentNameVectorizationSource.cs +++ /dev/null @@ -1,65 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// - /// Represents a vectorization source that makes internal service calls against an Azure OpenAI embedding model - /// deployment. In contrast with the endpoint-based vectorization source, a deployment-name-based vectorization source - /// must be part of the same Azure OpenAI resource but can be used even in private networks. - /// - internal partial class InternalAzureChatDataSourceDeploymentNameVectorizationSource : DataSourceVectorizer - { - /// Initializes a new instance of . - /// - /// The embedding model deployment to use for vectorization. This deployment must exist within the same Azure OpenAI - /// resource as the model deployment being used for chat completions. - /// - /// is null. - public InternalAzureChatDataSourceDeploymentNameVectorizationSource(string deploymentName) - { - Argument.AssertNotNull(deploymentName, nameof(deploymentName)); - - Type = "deployment_name"; - DeploymentName = deploymentName; - } - - /// Initializes a new instance of . - /// The differentiating identifier for the concrete vectorization source. - /// Keeps track of any properties unknown to the library. - /// - /// The embedding model deployment to use for vectorization. This deployment must exist within the same Azure OpenAI - /// resource as the model deployment being used for chat completions. - /// - /// - /// The number of dimensions to request on embeddings. - /// Only supported in 'text-embedding-3' and later models. - /// - internal InternalAzureChatDataSourceDeploymentNameVectorizationSource(string type, IDictionary serializedAdditionalRawData, string deploymentName, int? dimensions) : base(type, serializedAdditionalRawData) - { - DeploymentName = deploymentName; - Dimensions = dimensions; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureChatDataSourceDeploymentNameVectorizationSource() - { - } - - /// - /// The embedding model deployment to use for vectorization. This deployment must exist within the same Azure OpenAI - /// resource as the model deployment being used for chat completions. - /// - internal string DeploymentName { get; set; } - /// - /// The number of dimensions to request on embeddings. - /// Only supported in 'text-embedding-3' and later models. - /// - public int? Dimensions { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.Serialization.cs deleted file mode 100644 index b24dfb4f4137..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions : 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(InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("encoded_api_key") != true) - { - writer.WritePropertyName("encoded_api_key"u8); - writer.WriteStringValue(EncodedApiKey); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions 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(InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions DeserializeInternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string encodedApiKey = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("encoded_api_key"u8)) - { - encodedApiKey = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(type, serializedAdditionalRawData, encodedApiKey); - } - - 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(InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions 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 DeserializeInternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.cs deleted file mode 100644 index 36c145320c34..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.cs +++ /dev/null @@ -1,42 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureChatDataSourceEncodedApiKeyAuthenticationOptions. - internal partial class InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions : DataSourceAuthentication - { - /// Initializes a new instance of . - /// - /// is null. - public InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(string encodedApiKey) - { - Argument.AssertNotNull(encodedApiKey, nameof(encodedApiKey)); - - Type = "encoded_api_key"; - EncodedApiKey = encodedApiKey; - } - - /// Initializes a new instance of . - /// Discriminator. - /// Keeps track of any properties unknown to the library. - /// - internal InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(string type, IDictionary serializedAdditionalRawData, string encodedApiKey) : base(type, serializedAdditionalRawData) - { - EncodedApiKey = encodedApiKey; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions() - { - } - - /// Gets the encoded api key. - internal string EncodedApiKey { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEndpointVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEndpointVectorizationSource.Serialization.cs deleted file mode 100644 index e984e66bca8a..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEndpointVectorizationSource.Serialization.cs +++ /dev/null @@ -1,174 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceEndpointVectorizationSource : 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(InternalAzureChatDataSourceEndpointVectorizationSource)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("endpoint") != true) - { - writer.WritePropertyName("endpoint"u8); - writer.WriteStringValue(Endpoint.AbsoluteUri); - } - if (SerializedAdditionalRawData?.ContainsKey("authentication") != true) - { - writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); - } - if (SerializedAdditionalRawData?.ContainsKey("dimensions") != true && Optional.IsDefined(Dimensions)) - { - writer.WritePropertyName("dimensions"u8); - writer.WriteNumberValue(Dimensions.Value); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceEndpointVectorizationSource 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(InternalAzureChatDataSourceEndpointVectorizationSource)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceEndpointVectorizationSource(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceEndpointVectorizationSource DeserializeInternalAzureChatDataSourceEndpointVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - Uri endpoint = default; - DataSourceAuthentication authentication = default; - int? dimensions = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("endpoint"u8)) - { - endpoint = new Uri(property.Value.GetString()); - continue; - } - if (property.NameEquals("authentication"u8)) - { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(property.Value, options); - continue; - } - if (property.NameEquals("dimensions"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - dimensions = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceEndpointVectorizationSource(type, serializedAdditionalRawData, endpoint, authentication, dimensions); - } - - 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(InternalAzureChatDataSourceEndpointVectorizationSource)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceEndpointVectorizationSource 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 DeserializeInternalAzureChatDataSourceEndpointVectorizationSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceEndpointVectorizationSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceEndpointVectorizationSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceEndpointVectorizationSource(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEndpointVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEndpointVectorizationSource.cs deleted file mode 100644 index 38b036485065..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceEndpointVectorizationSource.cs +++ /dev/null @@ -1,80 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// Represents a vectorization source that makes public service calls against an Azure OpenAI embedding model deployment. - internal partial class InternalAzureChatDataSourceEndpointVectorizationSource : DataSourceVectorizer - { - /// Initializes a new instance of . - /// - /// Specifies the resource endpoint URL from which embeddings should be retrieved. - /// It should be in the format of: - /// https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. - /// The api-version query parameter is not allowed. - /// - /// - /// The authentication mechanism to use with the endpoint-based vectorization source. - /// Endpoint authentication supports API key and access token mechanisms. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// or is null. - public InternalAzureChatDataSourceEndpointVectorizationSource(Uri endpoint, DataSourceAuthentication authentication) - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNull(authentication, nameof(authentication)); - - Type = "endpoint"; - Endpoint = endpoint; - Authentication = authentication; - } - - /// Initializes a new instance of . - /// The differentiating identifier for the concrete vectorization source. - /// Keeps track of any properties unknown to the library. - /// - /// Specifies the resource endpoint URL from which embeddings should be retrieved. - /// It should be in the format of: - /// https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. - /// The api-version query parameter is not allowed. - /// - /// - /// The authentication mechanism to use with the endpoint-based vectorization source. - /// Endpoint authentication supports API key and access token mechanisms. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// The number of dimensions to request on embeddings. - /// Only supported in 'text-embedding-3' and later models. - /// - internal InternalAzureChatDataSourceEndpointVectorizationSource(string type, IDictionary serializedAdditionalRawData, Uri endpoint, DataSourceAuthentication authentication, int? dimensions) : base(type, serializedAdditionalRawData) - { - Endpoint = endpoint; - Authentication = authentication; - Dimensions = dimensions; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureChatDataSourceEndpointVectorizationSource() - { - } - - /// - /// Specifies the resource endpoint URL from which embeddings should be retrieved. - /// It should be in the format of: - /// https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. - /// The api-version query parameter is not allowed. - /// - internal Uri Endpoint { get; set; } - /// - /// The number of dimensions to request on embeddings. - /// Only supported in 'text-embedding-3' and later models. - /// - public int? Dimensions { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceIntegratedVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceIntegratedVectorizationSource.Serialization.cs deleted file mode 100644 index 92c61b0e631a..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceIntegratedVectorizationSource.Serialization.cs +++ /dev/null @@ -1,137 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceIntegratedVectorizationSource : 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(InternalAzureChatDataSourceIntegratedVectorizationSource)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceIntegratedVectorizationSource 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(InternalAzureChatDataSourceIntegratedVectorizationSource)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceIntegratedVectorizationSource(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceIntegratedVectorizationSource DeserializeInternalAzureChatDataSourceIntegratedVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceIntegratedVectorizationSource(type, serializedAdditionalRawData); - } - - 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(InternalAzureChatDataSourceIntegratedVectorizationSource)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceIntegratedVectorizationSource 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 DeserializeInternalAzureChatDataSourceIntegratedVectorizationSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceIntegratedVectorizationSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceIntegratedVectorizationSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceIntegratedVectorizationSource(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceIntegratedVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceIntegratedVectorizationSource.cs deleted file mode 100644 index 08fa29e39635..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceIntegratedVectorizationSource.cs +++ /dev/null @@ -1,27 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// Represents an integrated vectorization source as defined within the supporting search resource. - internal partial class InternalAzureChatDataSourceIntegratedVectorizationSource : DataSourceVectorizer - { - /// Initializes a new instance of . - public InternalAzureChatDataSourceIntegratedVectorizationSource() - { - Type = "integrated"; - } - - /// Initializes a new instance of . - /// The differentiating identifier for the concrete vectorization source. - /// Keeps track of any properties unknown to the library. - internal InternalAzureChatDataSourceIntegratedVectorizationSource(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.Serialization.cs deleted file mode 100644 index 3d1b11f308cc..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,159 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions : 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(InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("key") != true) - { - writer.WritePropertyName("key"u8); - writer.WriteStringValue(Key); - } - if (SerializedAdditionalRawData?.ContainsKey("key_id") != true) - { - writer.WritePropertyName("key_id"u8); - writer.WriteStringValue(KeyId); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions 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(InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions DeserializeInternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string key = default; - string keyId = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("key"u8)) - { - key = property.Value.GetString(); - continue; - } - if (property.NameEquals("key_id"u8)) - { - keyId = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(type, serializedAdditionalRawData, key, keyId); - } - - 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(InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions 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 DeserializeInternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.cs deleted file mode 100644 index 528d5880483e..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.cs +++ /dev/null @@ -1,49 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureChatDataSourceKeyAndKeyIdAuthenticationOptions. - internal partial class InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions : DataSourceAuthentication - { - /// Initializes a new instance of . - /// - /// - /// or is null. - public InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(string key, string keyId) - { - Argument.AssertNotNull(key, nameof(key)); - Argument.AssertNotNull(keyId, nameof(keyId)); - - Type = "key_and_key_id"; - Key = key; - KeyId = keyId; - } - - /// Initializes a new instance of . - /// Discriminator. - /// Keeps track of any properties unknown to the library. - /// - /// - internal InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(string type, IDictionary serializedAdditionalRawData, string key, string keyId) : base(type, serializedAdditionalRawData) - { - Key = key; - KeyId = keyId; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions() - { - } - - /// Gets the key. - internal string Key { get; set; } - /// Gets the key id. - internal string KeyId { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceModelIdVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceModelIdVectorizationSource.Serialization.cs deleted file mode 100644 index cbbae8276b91..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceModelIdVectorizationSource.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceModelIdVectorizationSource : 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(InternalAzureChatDataSourceModelIdVectorizationSource)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("model_id") != true) - { - writer.WritePropertyName("model_id"u8); - writer.WriteStringValue(ModelId); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceModelIdVectorizationSource 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(InternalAzureChatDataSourceModelIdVectorizationSource)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceModelIdVectorizationSource(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceModelIdVectorizationSource DeserializeInternalAzureChatDataSourceModelIdVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string modelId = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("model_id"u8)) - { - modelId = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceModelIdVectorizationSource(type, serializedAdditionalRawData, modelId); - } - - 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(InternalAzureChatDataSourceModelIdVectorizationSource)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceModelIdVectorizationSource 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 DeserializeInternalAzureChatDataSourceModelIdVectorizationSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceModelIdVectorizationSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceModelIdVectorizationSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceModelIdVectorizationSource(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceModelIdVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceModelIdVectorizationSource.cs deleted file mode 100644 index b4bf391b5bf6..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceModelIdVectorizationSource.cs +++ /dev/null @@ -1,45 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// - /// Represents a vectorization source that makes service calls based on a search service model ID. - /// This source type is currently only supported by Elasticsearch. - /// - internal partial class InternalAzureChatDataSourceModelIdVectorizationSource : DataSourceVectorizer - { - /// Initializes a new instance of . - /// The embedding model build ID to use for vectorization. - /// is null. - internal InternalAzureChatDataSourceModelIdVectorizationSource(string modelId) - { - Argument.AssertNotNull(modelId, nameof(modelId)); - - Type = "model_id"; - ModelId = modelId; - } - - /// Initializes a new instance of . - /// The differentiating identifier for the concrete vectorization source. - /// Keeps track of any properties unknown to the library. - /// The embedding model build ID to use for vectorization. - internal InternalAzureChatDataSourceModelIdVectorizationSource(string type, IDictionary serializedAdditionalRawData, string modelId) : base(type, serializedAdditionalRawData) - { - ModelId = modelId; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureChatDataSourceModelIdVectorizationSource() - { - } - - /// The embedding model build ID to use for vectorization. - internal string ModelId { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs deleted file mode 100644 index 3d97453fcfd2..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,137 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions : 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(InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions 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(InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions DeserializeInternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(type, serializedAdditionalRawData); - } - - 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(InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions 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 DeserializeInternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.cs deleted file mode 100644 index 6b64f501d4d7..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.cs +++ /dev/null @@ -1,27 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions. - internal partial class InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions : DataSourceAuthentication - { - /// Initializes a new instance of . - public InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions() - { - Type = "system_assigned_managed_identity"; - } - - /// Initializes a new instance of . - /// Discriminator. - /// Keeps track of any properties unknown to the library. - internal InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs deleted file mode 100644 index 92a62ed8c6bb..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions : 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(InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("managed_identity_resource_id") != true) - { - writer.WritePropertyName("managed_identity_resource_id"u8); - writer.WriteStringValue(ManagedIdentityResourceId); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions 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(InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions DeserializeInternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string managedIdentityResourceId = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("managed_identity_resource_id"u8)) - { - managedIdentityResourceId = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(type, serializedAdditionalRawData, managedIdentityResourceId); - } - - 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(InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions 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 DeserializeInternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.cs deleted file mode 100644 index 97f938b2bd14..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.cs +++ /dev/null @@ -1,42 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions. - internal partial class InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions : DataSourceAuthentication - { - /// Initializes a new instance of . - /// - /// is null. - public InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(string managedIdentityResourceId) - { - Argument.AssertNotNull(managedIdentityResourceId, nameof(managedIdentityResourceId)); - - Type = "user_assigned_managed_identity"; - ManagedIdentityResourceId = managedIdentityResourceId; - } - - /// Initializes a new instance of . - /// Discriminator. - /// Keeps track of any properties unknown to the library. - /// - internal InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(string type, IDictionary serializedAdditionalRawData, string managedIdentityResourceId) : base(type, serializedAdditionalRawData) - { - ManagedIdentityResourceId = managedIdentityResourceId; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions() - { - } - - /// Gets the managed identity resource id. - internal string ManagedIdentityResourceId { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.Serialization.cs deleted file mode 100644 index 4fa05a6eb3b8..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,159 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions : 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(InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("username") != true) - { - writer.WritePropertyName("username"u8); - writer.WriteStringValue(Username); - } - if (SerializedAdditionalRawData?.ContainsKey("password") != true) - { - writer.WritePropertyName("password"u8); - writer.WriteStringValue(Password); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions 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(InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions DeserializeInternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string username = default; - string password = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("username"u8)) - { - username = property.Value.GetString(); - continue; - } - if (property.NameEquals("password"u8)) - { - password = property.Value.GetString(); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(type, serializedAdditionalRawData, username, password); - } - - 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(InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions 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 DeserializeInternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.cs deleted file mode 100644 index c72d02a0de9b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.cs +++ /dev/null @@ -1,49 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureChatDataSourceUsernameAndPasswordAuthenticationOptions. - internal partial class InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions : DataSourceAuthentication - { - /// Initializes a new instance of . - /// - /// - /// or is null. - public InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(string username, string password) - { - Argument.AssertNotNull(username, nameof(username)); - Argument.AssertNotNull(password, nameof(password)); - - Type = "username_and_password"; - Username = username; - Password = password; - } - - /// Initializes a new instance of . - /// Discriminator. - /// Keeps track of any properties unknown to the library. - /// - /// - internal InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(string type, IDictionary serializedAdditionalRawData, string username, string password) : base(type, serializedAdditionalRawData) - { - Username = username; - Password = password; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions() - { - } - - /// Gets the username. - internal string Username { get; set; } - /// Gets the password. - internal string Password { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistIdResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistIdResult.Serialization.cs deleted file mode 100644 index e00fc19ccf89..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistIdResult.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterBlocklistIdResult : 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(InternalAzureContentFilterBlocklistIdResult)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - 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(); - } - - InternalAzureContentFilterBlocklistIdResult 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(InternalAzureContentFilterBlocklistIdResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureContentFilterBlocklistIdResult(document.RootElement, options); - } - - internal static InternalAzureContentFilterBlocklistIdResult DeserializeInternalAzureContentFilterBlocklistIdResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - bool filtered = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("filtered"u8)) - { - filtered = property.Value.GetBoolean(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureContentFilterBlocklistIdResult(id, filtered, serializedAdditionalRawData); - } - - 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(InternalAzureContentFilterBlocklistIdResult)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureContentFilterBlocklistIdResult 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 DeserializeInternalAzureContentFilterBlocklistIdResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterBlocklistIdResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalAzureContentFilterBlocklistIdResult FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureContentFilterBlocklistIdResult(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistIdResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistIdResult.cs deleted file mode 100644 index 1950182689c4..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistIdResult.cs +++ /dev/null @@ -1,81 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// - /// A content filter result item that associates an existing custom blocklist ID with a value indicating whether or not - /// the corresponding blocklist resulted in content being filtered. - /// - internal partial class InternalAzureContentFilterBlocklistIdResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// The ID of the custom blocklist associated with the filtered status. - /// Whether the associated blocklist resulted in the content being filtered. - /// is null. - internal InternalAzureContentFilterBlocklistIdResult(string id, bool filtered) - { - Argument.AssertNotNull(id, nameof(id)); - - Id = id; - Filtered = filtered; - } - - /// Initializes a new instance of . - /// The ID of the custom blocklist associated with the filtered status. - /// Whether the associated blocklist resulted in the content being filtered. - /// Keeps track of any properties unknown to the library. - internal InternalAzureContentFilterBlocklistIdResult(string id, bool filtered, IDictionary serializedAdditionalRawData) - { - Id = id; - Filtered = filtered; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureContentFilterBlocklistIdResult() - { - } - - /// The ID of the custom blocklist associated with the filtered status. - internal string Id { get; set; } - /// Whether the associated blocklist resulted in the content being filtered. - internal bool Filtered { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistResultDetail.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistResultDetail.Serialization.cs deleted file mode 100644 index 02ac4d99cbe9..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterBlocklistResultDetail.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterBlocklistResultDetail : 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(InternalAzureContentFilterBlocklistResultDetail)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (SerializedAdditionalRawData?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - InternalAzureContentFilterBlocklistResultDetail 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(InternalAzureContentFilterBlocklistResultDetail)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureContentFilterBlocklistResultDetail(document.RootElement, options); - } - - internal static InternalAzureContentFilterBlocklistResultDetail DeserializeInternalAzureContentFilterBlocklistResultDetail(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool filtered = default; - string id = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("filtered"u8)) - { - filtered = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureContentFilterBlocklistResultDetail(filtered, id, serializedAdditionalRawData); - } - - 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(InternalAzureContentFilterBlocklistResultDetail)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureContentFilterBlocklistResultDetail 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 DeserializeInternalAzureContentFilterBlocklistResultDetail(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterBlocklistResultDetail)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalAzureContentFilterBlocklistResultDetail FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureContentFilterBlocklistResultDetail(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResults.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResults.cs deleted file mode 100644 index 8c654f48774d..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResults.cs +++ /dev/null @@ -1,169 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// The AzureContentFilterResultForPromptContentFilterResults. - internal partial class InternalAzureContentFilterResultForPromptContentFilterResults - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// - /// A detection result that describes user prompt injection attacks, where malicious users deliberately exploit - /// system vulnerabilities to elicit unauthorized behavior from the LLM. This could lead to inappropriate content - /// generation or violations of system-imposed restrictions. - /// - /// - /// A detection result that describes attacks on systems powered by Generative AI models that can happen every time - /// an application processes information that wasn’t directly authored by either the developer of the application or - /// the user. - /// - /// or is null. - internal InternalAzureContentFilterResultForPromptContentFilterResults(ContentFilterDetectionResult jailbreak, ContentFilterDetectionResult indirectAttack) - { - Argument.AssertNotNull(jailbreak, nameof(jailbreak)); - Argument.AssertNotNull(indirectAttack, nameof(indirectAttack)); - - Jailbreak = jailbreak; - IndirectAttack = indirectAttack; - } - - /// Initializes a new instance of . - /// - /// A content filter category for language related to anatomical organs and genitals, romantic relationships, acts - /// portrayed in erotic or affectionate terms, pregnancy, physical sexual acts, including those portrayed as an - /// assault or a forced sexual violent act against one's will, prostitution, pornography, and abuse. - /// - /// - /// A content filter category that can refer to any content that attacks or uses pejorative or discriminatory - /// language with reference to a person or identity group based on certain differentiating attributes of these groups - /// including but not limited to race, ethnicity, nationality, gender identity and expression, sexual orientation, - /// religion, immigration status, ability status, personal appearance, and body size. - /// - /// - /// A content filter category for language related to physical actions intended to hurt, injure, damage, or kill - /// someone or something; describes weapons, guns and related entities, such as manufactures, associations, - /// legislation, and so on. - /// - /// - /// A content filter category that describes language related to physical actions intended to purposely hurt, injure, - /// damage one's body or kill oneself. - /// - /// - /// A detection result that identifies whether crude, vulgar, or otherwise objection language is present in the - /// content. - /// - /// A collection of binary filtering outcomes for configured custom blocklists. - /// If present, details about an error that prevented content filtering from completing its evaluation. - /// - /// A detection result that describes user prompt injection attacks, where malicious users deliberately exploit - /// system vulnerabilities to elicit unauthorized behavior from the LLM. This could lead to inappropriate content - /// generation or violations of system-imposed restrictions. - /// - /// - /// A detection result that describes attacks on systems powered by Generative AI models that can happen every time - /// an application processes information that wasn’t directly authored by either the developer of the application or - /// the user. - /// - /// Keeps track of any properties unknown to the library. - internal InternalAzureContentFilterResultForPromptContentFilterResults(ContentFilterSeverityResult sexual, ContentFilterSeverityResult hate, ContentFilterSeverityResult violence, ContentFilterSeverityResult selfHarm, ContentFilterDetectionResult profanity, ContentFilterBlocklistResult customBlocklists, InternalAzureContentFilterResultForPromptContentFilterResultsError error, ContentFilterDetectionResult jailbreak, ContentFilterDetectionResult indirectAttack, IDictionary serializedAdditionalRawData) - { - Sexual = sexual; - Hate = hate; - Violence = violence; - SelfHarm = selfHarm; - Profanity = profanity; - CustomBlocklists = customBlocklists; - Error = error; - Jailbreak = jailbreak; - IndirectAttack = indirectAttack; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureContentFilterResultForPromptContentFilterResults() - { - } - - /// - /// A content filter category for language related to anatomical organs and genitals, romantic relationships, acts - /// portrayed in erotic or affectionate terms, pregnancy, physical sexual acts, including those portrayed as an - /// assault or a forced sexual violent act against one's will, prostitution, pornography, and abuse. - /// - internal ContentFilterSeverityResult Sexual { get; set; } - /// - /// A content filter category that can refer to any content that attacks or uses pejorative or discriminatory - /// language with reference to a person or identity group based on certain differentiating attributes of these groups - /// including but not limited to race, ethnicity, nationality, gender identity and expression, sexual orientation, - /// religion, immigration status, ability status, personal appearance, and body size. - /// - internal ContentFilterSeverityResult Hate { get; set; } - /// - /// A content filter category for language related to physical actions intended to hurt, injure, damage, or kill - /// someone or something; describes weapons, guns and related entities, such as manufactures, associations, - /// legislation, and so on. - /// - internal ContentFilterSeverityResult Violence { get; set; } - /// - /// A content filter category that describes language related to physical actions intended to purposely hurt, injure, - /// damage one's body or kill oneself. - /// - internal ContentFilterSeverityResult SelfHarm { get; set; } - /// - /// A detection result that identifies whether crude, vulgar, or otherwise objection language is present in the - /// content. - /// - internal ContentFilterDetectionResult Profanity { get; set; } - /// A collection of binary filtering outcomes for configured custom blocklists. - internal ContentFilterBlocklistResult CustomBlocklists { get; set; } - /// If present, details about an error that prevented content filtering from completing its evaluation. - internal InternalAzureContentFilterResultForPromptContentFilterResultsError Error { get; set; } - /// - /// A detection result that describes user prompt injection attacks, where malicious users deliberately exploit - /// system vulnerabilities to elicit unauthorized behavior from the LLM. This could lead to inappropriate content - /// generation or violations of system-imposed restrictions. - /// - internal ContentFilterDetectionResult Jailbreak { get; set; } - /// - /// A detection result that describes attacks on systems powered by Generative AI models that can happen every time - /// an application processes information that wasn’t directly authored by either the developer of the application or - /// the user. - /// - internal ContentFilterDetectionResult IndirectAttack { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResultsError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResultsError.Serialization.cs deleted file mode 100644 index 24d22365ed03..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureContentFilterResultForPromptContentFilterResultsError.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterResultForPromptContentFilterResultsError : 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(InternalAzureContentFilterResultForPromptContentFilterResultsError)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true) - { - writer.WritePropertyName("code"u8); - writer.WriteNumberValue(Code); - } - if (SerializedAdditionalRawData?.ContainsKey("message") != true) - { - writer.WritePropertyName("message"u8); - writer.WriteStringValue(Message); - } - 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(); - } - - InternalAzureContentFilterResultForPromptContentFilterResultsError 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(InternalAzureContentFilterResultForPromptContentFilterResultsError)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureContentFilterResultForPromptContentFilterResultsError(document.RootElement, options); - } - - internal static InternalAzureContentFilterResultForPromptContentFilterResultsError DeserializeInternalAzureContentFilterResultForPromptContentFilterResultsError(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int code = default; - string message = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("code"u8)) - { - code = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("message"u8)) - { - message = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureContentFilterResultForPromptContentFilterResultsError(code, message, serializedAdditionalRawData); - } - - 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(InternalAzureContentFilterResultForPromptContentFilterResultsError)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureContentFilterResultForPromptContentFilterResultsError 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 DeserializeInternalAzureContentFilterResultForPromptContentFilterResultsError(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterResultForPromptContentFilterResultsError)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalAzureContentFilterResultForPromptContentFilterResultsError FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureContentFilterResultForPromptContentFilterResultsError(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureCosmosDBChatDataSourceParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureCosmosDBChatDataSourceParameters.cs deleted file mode 100644 index 90c5774584cc..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureCosmosDBChatDataSourceParameters.cs +++ /dev/null @@ -1,153 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureCosmosDBChatDataSourceParameters. - internal partial class InternalAzureCosmosDBChatDataSourceParameters - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// - /// - /// - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// , , , , or is null. - public InternalAzureCosmosDBChatDataSourceParameters(string containerName, string databaseName, DataSourceVectorizer vectorizationSource, string indexName, DataSourceAuthentication authentication, DataSourceFieldMappings fieldMappings) - { - Argument.AssertNotNull(containerName, nameof(containerName)); - Argument.AssertNotNull(databaseName, nameof(databaseName)); - Argument.AssertNotNull(vectorizationSource, nameof(vectorizationSource)); - Argument.AssertNotNull(indexName, nameof(indexName)); - Argument.AssertNotNull(authentication, nameof(authentication)); - Argument.AssertNotNull(fieldMappings, nameof(fieldMappings)); - - _internalIncludeContexts = new ChangeTrackingList(); - ContainerName = containerName; - DatabaseName = databaseName; - VectorizationSource = vectorizationSource; - IndexName = indexName; - Authentication = authentication; - FieldMappings = fieldMappings; - } - - /// Initializes a new instance of . - /// The configured number of documents to feature in the query. - /// Whether queries should be restricted to use of the indexed data. - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - /// - /// The output context properties to include on the response. - /// By default, citations and intent will be requested. - /// - /// - /// - /// - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// Keeps track of any properties unknown to the library. - internal InternalAzureCosmosDBChatDataSourceParameters(int? topNDocuments, bool? inScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList internalIncludeContexts, string containerName, string databaseName, DataSourceVectorizer vectorizationSource, string indexName, DataSourceAuthentication authentication, DataSourceFieldMappings fieldMappings, IDictionary serializedAdditionalRawData) - { - TopNDocuments = topNDocuments; - InScope = inScope; - Strictness = strictness; - MaxSearchQueries = maxSearchQueries; - AllowPartialResult = allowPartialResult; - _internalIncludeContexts = internalIncludeContexts; - ContainerName = containerName; - DatabaseName = databaseName; - VectorizationSource = vectorizationSource; - IndexName = indexName; - Authentication = authentication; - FieldMappings = fieldMappings; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureCosmosDBChatDataSourceParameters() - { - } - - /// The configured number of documents to feature in the query. - public int? TopNDocuments { get; set; } - /// Whether queries should be restricted to use of the indexed data. - public bool? InScope { get; set; } - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - public int? Strictness { get; set; } - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - public int? MaxSearchQueries { get; set; } - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - public bool? AllowPartialResult { get; set; } - /// Gets the container name. - internal string ContainerName { get; set; } - /// Gets the database name. - internal string DatabaseName { get; set; } - /// Gets the index name. - internal string IndexName { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIChatErrorInnerError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIChatErrorInnerError.Serialization.cs deleted file mode 100644 index 0a58496a1938..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIChatErrorInnerError.Serialization.cs +++ /dev/null @@ -1,167 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureOpenAIChatErrorInnerError : 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(InternalAzureOpenAIChatErrorInnerError)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true && Optional.IsDefined(Code)) - { - writer.WritePropertyName("code"u8); - writer.WriteStringValue(Code.Value.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("revised_prompt") != true && Optional.IsDefined(RevisedPrompt)) - { - writer.WritePropertyName("revised_prompt"u8); - writer.WriteStringValue(RevisedPrompt); - } - if (SerializedAdditionalRawData?.ContainsKey("content_filter_results") != true && Optional.IsDefined(ContentFilterResults)) - { - writer.WritePropertyName("content_filter_results"u8); - writer.WriteObjectValue(ContentFilterResults, 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(); - } - - InternalAzureOpenAIChatErrorInnerError 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(InternalAzureOpenAIChatErrorInnerError)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureOpenAIChatErrorInnerError(document.RootElement, options); - } - - internal static InternalAzureOpenAIChatErrorInnerError DeserializeInternalAzureOpenAIChatErrorInnerError(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - InternalAzureOpenAIChatErrorInnerErrorCode? code = default; - string revisedPrompt = default; - RequestContentFilterResult contentFilterResults = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("code"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - code = new InternalAzureOpenAIChatErrorInnerErrorCode(property.Value.GetString()); - continue; - } - if (property.NameEquals("revised_prompt"u8)) - { - revisedPrompt = property.Value.GetString(); - continue; - } - if (property.NameEquals("content_filter_results"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - contentFilterResults = RequestContentFilterResult.DeserializeRequestContentFilterResult(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureOpenAIChatErrorInnerError(code, revisedPrompt, contentFilterResults, serializedAdditionalRawData); - } - - 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(InternalAzureOpenAIChatErrorInnerError)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureOpenAIChatErrorInnerError 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 DeserializeInternalAzureOpenAIChatErrorInnerError(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureOpenAIChatErrorInnerError)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalAzureOpenAIChatErrorInnerError FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureOpenAIChatErrorInnerError(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIChatErrorInnerError.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIChatErrorInnerError.cs deleted file mode 100644 index 2209ed339feb..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIChatErrorInnerError.cs +++ /dev/null @@ -1,70 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// The AzureOpenAIChatErrorInnerError. - internal partial class InternalAzureOpenAIChatErrorInnerError - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal InternalAzureOpenAIChatErrorInnerError() - { - } - - /// Initializes a new instance of . - /// The code associated with the inner error. - /// If applicable, the modified prompt used for generation. - /// The content filter result details associated with the inner error. - /// Keeps track of any properties unknown to the library. - internal InternalAzureOpenAIChatErrorInnerError(InternalAzureOpenAIChatErrorInnerErrorCode? code, string revisedPrompt, RequestContentFilterResult contentFilterResults, IDictionary serializedAdditionalRawData) - { - Code = code; - RevisedPrompt = revisedPrompt; - ContentFilterResults = contentFilterResults; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The code associated with the inner error. - internal InternalAzureOpenAIChatErrorInnerErrorCode? Code { get; set; } - /// If applicable, the modified prompt used for generation. - internal string RevisedPrompt { get; set; } - /// The content filter result details associated with the inner error. - internal RequestContentFilterResult ContentFilterResults { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIChatErrorInnerErrorCode.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIChatErrorInnerErrorCode.cs deleted file mode 100644 index 1e1ab2f0c352..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIChatErrorInnerErrorCode.cs +++ /dev/null @@ -1,46 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI -{ - /// The AzureOpenAIChatErrorInnerError_code. - internal readonly partial struct InternalAzureOpenAIChatErrorInnerErrorCode : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public InternalAzureOpenAIChatErrorInnerErrorCode(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ResponsibleAIPolicyViolationValue = "ResponsibleAIPolicyViolation"; - - /// ResponsibleAIPolicyViolation. - internal static InternalAzureOpenAIChatErrorInnerErrorCode ResponsibleAIPolicyViolation { get; set; } = new InternalAzureOpenAIChatErrorInnerErrorCode(ResponsibleAIPolicyViolationValue); - /// Determines if two values are the same. - public static bool operator ==(InternalAzureOpenAIChatErrorInnerErrorCode left, InternalAzureOpenAIChatErrorInnerErrorCode right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(InternalAzureOpenAIChatErrorInnerErrorCode left, InternalAzureOpenAIChatErrorInnerErrorCode right) => !left.Equals(right); - /// Converts a string to a . - public static implicit operator InternalAzureOpenAIChatErrorInnerErrorCode(string value) => new InternalAzureOpenAIChatErrorInnerErrorCode(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalAzureOpenAIChatErrorInnerErrorCode other && Equals(other); - /// - public bool Equals(InternalAzureOpenAIChatErrorInnerErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIDalleErrorInnerError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIDalleErrorInnerError.Serialization.cs deleted file mode 100644 index 36e2e5564ba2..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIDalleErrorInnerError.Serialization.cs +++ /dev/null @@ -1,167 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureOpenAIDalleErrorInnerError : 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(InternalAzureOpenAIDalleErrorInnerError)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("code") != true && Optional.IsDefined(Code)) - { - writer.WritePropertyName("code"u8); - writer.WriteStringValue(Code.Value.ToString()); - } - if (SerializedAdditionalRawData?.ContainsKey("revised_prompt") != true && Optional.IsDefined(RevisedPrompt)) - { - writer.WritePropertyName("revised_prompt"u8); - writer.WriteStringValue(RevisedPrompt); - } - if (SerializedAdditionalRawData?.ContainsKey("content_filter_results") != true && Optional.IsDefined(ContentFilterResults)) - { - writer.WritePropertyName("content_filter_results"u8); - writer.WriteObjectValue(ContentFilterResults, 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(); - } - - InternalAzureOpenAIDalleErrorInnerError 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(InternalAzureOpenAIDalleErrorInnerError)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureOpenAIDalleErrorInnerError(document.RootElement, options); - } - - internal static InternalAzureOpenAIDalleErrorInnerError DeserializeInternalAzureOpenAIDalleErrorInnerError(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - InternalAzureOpenAIDalleErrorInnerErrorCode? code = default; - string revisedPrompt = default; - RequestImageContentFilterResult contentFilterResults = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("code"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - code = new InternalAzureOpenAIDalleErrorInnerErrorCode(property.Value.GetString()); - continue; - } - if (property.NameEquals("revised_prompt"u8)) - { - revisedPrompt = property.Value.GetString(); - continue; - } - if (property.NameEquals("content_filter_results"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - contentFilterResults = RequestImageContentFilterResult.DeserializeRequestImageContentFilterResult(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureOpenAIDalleErrorInnerError(code, revisedPrompt, contentFilterResults, serializedAdditionalRawData); - } - - 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(InternalAzureOpenAIDalleErrorInnerError)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureOpenAIDalleErrorInnerError 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 DeserializeInternalAzureOpenAIDalleErrorInnerError(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureOpenAIDalleErrorInnerError)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalAzureOpenAIDalleErrorInnerError FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureOpenAIDalleErrorInnerError(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIDalleErrorInnerError.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIDalleErrorInnerError.cs deleted file mode 100644 index 415434fba3a0..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIDalleErrorInnerError.cs +++ /dev/null @@ -1,70 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// The AzureOpenAIDalleErrorInnerError. - internal partial class InternalAzureOpenAIDalleErrorInnerError - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal InternalAzureOpenAIDalleErrorInnerError() - { - } - - /// Initializes a new instance of . - /// The code associated with the inner error. - /// If applicable, the modified prompt used for generation. - /// The content filter result details associated with the inner error. - /// Keeps track of any properties unknown to the library. - internal InternalAzureOpenAIDalleErrorInnerError(InternalAzureOpenAIDalleErrorInnerErrorCode? code, string revisedPrompt, RequestImageContentFilterResult contentFilterResults, IDictionary serializedAdditionalRawData) - { - Code = code; - RevisedPrompt = revisedPrompt; - ContentFilterResults = contentFilterResults; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// The code associated with the inner error. - internal InternalAzureOpenAIDalleErrorInnerErrorCode? Code { get; set; } - /// If applicable, the modified prompt used for generation. - internal string RevisedPrompt { get; set; } - /// The content filter result details associated with the inner error. - internal RequestImageContentFilterResult ContentFilterResults { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIDalleErrorInnerErrorCode.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIDalleErrorInnerErrorCode.cs deleted file mode 100644 index 35cf2d97866f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureOpenAIDalleErrorInnerErrorCode.cs +++ /dev/null @@ -1,46 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI -{ - /// The AzureOpenAIDalleErrorInnerError_code. - internal readonly partial struct InternalAzureOpenAIDalleErrorInnerErrorCode : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public InternalAzureOpenAIDalleErrorInnerErrorCode(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ResponsibleAIPolicyViolationValue = "ResponsibleAIPolicyViolation"; - - /// ResponsibleAIPolicyViolation. - internal static InternalAzureOpenAIDalleErrorInnerErrorCode ResponsibleAIPolicyViolation { get; set; } = new InternalAzureOpenAIDalleErrorInnerErrorCode(ResponsibleAIPolicyViolationValue); - /// Determines if two values are the same. - public static bool operator ==(InternalAzureOpenAIDalleErrorInnerErrorCode left, InternalAzureOpenAIDalleErrorInnerErrorCode right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(InternalAzureOpenAIDalleErrorInnerErrorCode left, InternalAzureOpenAIDalleErrorInnerErrorCode right) => !left.Equals(right); - /// Converts a string to a . - public static implicit operator InternalAzureOpenAIDalleErrorInnerErrorCode(string value) => new InternalAzureOpenAIDalleErrorInnerErrorCode(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalAzureOpenAIDalleErrorInnerErrorCode other && Equals(other); - /// - public bool Equals(InternalAzureOpenAIDalleErrorInnerErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureSearchChatDataSourceParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureSearchChatDataSourceParameters.cs deleted file mode 100644 index f46714e50404..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureSearchChatDataSourceParameters.cs +++ /dev/null @@ -1,152 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureSearchChatDataSourceParameters. - internal partial class InternalAzureSearchChatDataSourceParameters - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// The absolute endpoint path for the Azure Search resource to use. - /// The name of the index to use, as specified in the Azure Search resource. - /// - /// The authentication mechanism to use with Azure Search. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// , or is null. - public InternalAzureSearchChatDataSourceParameters(Uri endpoint, string indexName, DataSourceAuthentication authentication) - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNull(indexName, nameof(indexName)); - Argument.AssertNotNull(authentication, nameof(authentication)); - - _internalIncludeContexts = new ChangeTrackingList(); - Endpoint = endpoint; - IndexName = indexName; - Authentication = authentication; - } - - /// Initializes a new instance of . - /// The configured number of documents to feature in the query. - /// Whether queries should be restricted to use of the indexed data. - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - /// - /// The output context properties to include on the response. - /// By default, citations and intent will be requested. - /// - /// The absolute endpoint path for the Azure Search resource to use. - /// The name of the index to use, as specified in the Azure Search resource. - /// - /// The authentication mechanism to use with Azure Search. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// The field mappings to use with the Azure Search resource. - /// The query type for the Azure Search resource to use. - /// Additional semantic configuration for the query. - /// A filter to apply to the search. - /// - /// The vectorization source to use with Azure Search. - /// Supported sources for Azure Search include endpoint, deployment name, and integrated. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// Keeps track of any properties unknown to the library. - internal InternalAzureSearchChatDataSourceParameters(int? topNDocuments, bool? inScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList internalIncludeContexts, Uri endpoint, string indexName, DataSourceAuthentication authentication, DataSourceFieldMappings fieldMappings, DataSourceQueryType? queryType, string semanticConfiguration, string filter, DataSourceVectorizer vectorizationSource, IDictionary serializedAdditionalRawData) - { - TopNDocuments = topNDocuments; - InScope = inScope; - Strictness = strictness; - MaxSearchQueries = maxSearchQueries; - AllowPartialResult = allowPartialResult; - _internalIncludeContexts = internalIncludeContexts; - Endpoint = endpoint; - IndexName = indexName; - Authentication = authentication; - FieldMappings = fieldMappings; - QueryType = queryType; - SemanticConfiguration = semanticConfiguration; - Filter = filter; - VectorizationSource = vectorizationSource; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal InternalAzureSearchChatDataSourceParameters() - { - } - - /// The configured number of documents to feature in the query. - public int? TopNDocuments { get; set; } - /// Whether queries should be restricted to use of the indexed data. - public bool? InScope { get; set; } - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - public int? Strictness { get; set; } - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - public int? MaxSearchQueries { get; set; } - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - public bool? AllowPartialResult { get; set; } - /// The absolute endpoint path for the Azure Search resource to use. - internal Uri Endpoint { get; set; } - /// The name of the index to use, as specified in the Azure Search resource. - internal string IndexName { get; set; } - /// Additional semantic configuration for the query. - public string SemanticConfiguration { get; set; } - /// A filter to apply to the search. - public string Filter { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureSearchChatDataSourceParametersIncludeContext.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureSearchChatDataSourceParametersIncludeContext.cs deleted file mode 100644 index 90e6d867660d..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureSearchChatDataSourceParametersIncludeContext.cs +++ /dev/null @@ -1,52 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI.Chat -{ - /// The AzureSearchChatDataSourceParametersIncludeContext. - internal readonly partial struct InternalAzureSearchChatDataSourceParametersIncludeContext : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public InternalAzureSearchChatDataSourceParametersIncludeContext(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string CitationsValue = "citations"; - private const string IntentValue = "intent"; - private const string AllRetrievedDocumentsValue = "all_retrieved_documents"; - - /// citations. - internal static InternalAzureSearchChatDataSourceParametersIncludeContext Citations { get; set; } = new InternalAzureSearchChatDataSourceParametersIncludeContext(CitationsValue); - /// intent. - internal static InternalAzureSearchChatDataSourceParametersIncludeContext Intent { get; set; } = new InternalAzureSearchChatDataSourceParametersIncludeContext(IntentValue); - /// all_retrieved_documents. - internal static InternalAzureSearchChatDataSourceParametersIncludeContext AllRetrievedDocuments { get; set; } = new InternalAzureSearchChatDataSourceParametersIncludeContext(AllRetrievedDocumentsValue); - /// Determines if two values are the same. - public static bool operator ==(InternalAzureSearchChatDataSourceParametersIncludeContext left, InternalAzureSearchChatDataSourceParametersIncludeContext right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(InternalAzureSearchChatDataSourceParametersIncludeContext left, InternalAzureSearchChatDataSourceParametersIncludeContext right) => !left.Equals(right); - /// Converts a string to a . - public static implicit operator InternalAzureSearchChatDataSourceParametersIncludeContext(string value) => new InternalAzureSearchChatDataSourceParametersIncludeContext(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalAzureSearchChatDataSourceParametersIncludeContext other && Equals(other); - /// - public bool Equals(InternalAzureSearchChatDataSourceParametersIncludeContext other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalElasticsearchChatDataSourceParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalElasticsearchChatDataSourceParameters.cs deleted file mode 100644 index dcd3601dd9f7..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalElasticsearchChatDataSourceParameters.cs +++ /dev/null @@ -1,140 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The ElasticsearchChatDataSourceParameters. - internal partial class InternalElasticsearchChatDataSourceParameters - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// - /// - /// - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// , or is null. - public InternalElasticsearchChatDataSourceParameters(Uri endpoint, string indexName, DataSourceAuthentication authentication) - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNull(indexName, nameof(indexName)); - Argument.AssertNotNull(authentication, nameof(authentication)); - - _internalIncludeContexts = new ChangeTrackingList(); - Endpoint = endpoint; - IndexName = indexName; - Authentication = authentication; - } - - /// Initializes a new instance of . - /// The configured number of documents to feature in the query. - /// Whether queries should be restricted to use of the indexed data. - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - /// - /// The output context properties to include on the response. - /// By default, citations and intent will be requested. - /// - /// - /// - /// - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// - /// - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// Keeps track of any properties unknown to the library. - internal InternalElasticsearchChatDataSourceParameters(int? topNDocuments, bool? inScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList internalIncludeContexts, Uri endpoint, string indexName, DataSourceAuthentication authentication, DataSourceFieldMappings fieldMappings, DataSourceQueryType? queryType, DataSourceVectorizer vectorizationSource, IDictionary serializedAdditionalRawData) - { - TopNDocuments = topNDocuments; - InScope = inScope; - Strictness = strictness; - MaxSearchQueries = maxSearchQueries; - AllowPartialResult = allowPartialResult; - _internalIncludeContexts = internalIncludeContexts; - Endpoint = endpoint; - IndexName = indexName; - Authentication = authentication; - FieldMappings = fieldMappings; - QueryType = queryType; - VectorizationSource = vectorizationSource; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal InternalElasticsearchChatDataSourceParameters() - { - } - - /// The configured number of documents to feature in the query. - public int? TopNDocuments { get; set; } - /// Whether queries should be restricted to use of the indexed data. - public bool? InScope { get; set; } - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - public int? Strictness { get; set; } - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - public int? MaxSearchQueries { get; set; } - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - public bool? AllowPartialResult { get; set; } - /// Gets the endpoint. - internal Uri Endpoint { get; set; } - /// Gets the index name. - internal string IndexName { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalMongoDBChatDataSourceParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalMongoDBChatDataSourceParameters.cs deleted file mode 100644 index 52ccc319dc6f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalMongoDBChatDataSourceParameters.cs +++ /dev/null @@ -1,181 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The MongoDBChatDataSourceParameters. - internal partial class InternalMongoDBChatDataSourceParameters - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// The name of the MongoDB cluster endpoint. - /// The name of the MongoDB database. - /// The name of the MongoDB collection. - /// The name of the MongoDB application. - /// The name of the MongoDB index. - /// - /// The authentication mechanism to use with Pinecone. - /// Supported authentication mechanisms for Pinecone include: username and password. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// The vectorization source to use as an embedding dependency for the MongoDB data source. - /// Supported vectorization sources for MongoDB include: endpoint, deployment name. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// Field mappings to apply to data used by the MongoDB data source. - /// Note that content and vector field mappings are required for MongoDB. - /// - /// , , , , , , or is null. - public InternalMongoDBChatDataSourceParameters(string endpoint, string databaseName, string collectionName, string appName, string indexName, DataSourceAuthentication authentication, DataSourceVectorizer embeddingDependency, DataSourceFieldMappings fieldMappings) - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNull(databaseName, nameof(databaseName)); - Argument.AssertNotNull(collectionName, nameof(collectionName)); - Argument.AssertNotNull(appName, nameof(appName)); - Argument.AssertNotNull(indexName, nameof(indexName)); - Argument.AssertNotNull(authentication, nameof(authentication)); - Argument.AssertNotNull(embeddingDependency, nameof(embeddingDependency)); - Argument.AssertNotNull(fieldMappings, nameof(fieldMappings)); - - _internalIncludeContexts = new ChangeTrackingList(); - Endpoint = endpoint; - DatabaseName = databaseName; - CollectionName = collectionName; - AppName = appName; - IndexName = indexName; - Authentication = authentication; - EmbeddingDependency = embeddingDependency; - FieldMappings = fieldMappings; - } - - /// Initializes a new instance of . - /// The configured number of documents to feature in the query. - /// Whether queries should be restricted to use of the indexed data. - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - /// - /// The output context properties to include on the response. - /// By default, citations and intent will be requested. - /// - /// The name of the MongoDB cluster endpoint. - /// The name of the MongoDB database. - /// The name of the MongoDB collection. - /// The name of the MongoDB application. - /// The name of the MongoDB index. - /// - /// The authentication mechanism to use with Pinecone. - /// Supported authentication mechanisms for Pinecone include: username and password. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// The vectorization source to use as an embedding dependency for the MongoDB data source. - /// Supported vectorization sources for MongoDB include: endpoint, deployment name. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// Field mappings to apply to data used by the MongoDB data source. - /// Note that content and vector field mappings are required for MongoDB. - /// - /// Keeps track of any properties unknown to the library. - internal InternalMongoDBChatDataSourceParameters(int? topNDocuments, bool? inScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList internalIncludeContexts, string endpoint, string databaseName, string collectionName, string appName, string indexName, DataSourceAuthentication authentication, DataSourceVectorizer embeddingDependency, DataSourceFieldMappings fieldMappings, IDictionary serializedAdditionalRawData) - { - TopNDocuments = topNDocuments; - InScope = inScope; - Strictness = strictness; - MaxSearchQueries = maxSearchQueries; - AllowPartialResult = allowPartialResult; - _internalIncludeContexts = internalIncludeContexts; - Endpoint = endpoint; - DatabaseName = databaseName; - CollectionName = collectionName; - AppName = appName; - IndexName = indexName; - Authentication = authentication; - EmbeddingDependency = embeddingDependency; - FieldMappings = fieldMappings; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal InternalMongoDBChatDataSourceParameters() - { - } - - /// The configured number of documents to feature in the query. - public int? TopNDocuments { get; set; } - /// Whether queries should be restricted to use of the indexed data. - public bool? InScope { get; set; } - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - public int? Strictness { get; set; } - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - public int? MaxSearchQueries { get; set; } - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - public bool? AllowPartialResult { get; set; } - /// The name of the MongoDB cluster endpoint. - internal string Endpoint { get; set; } - /// The name of the MongoDB database. - internal string DatabaseName { get; set; } - /// The name of the MongoDB collection. - internal string CollectionName { get; set; } - /// The name of the MongoDB application. - internal string AppName { get; set; } - /// The name of the MongoDB index. - internal string IndexName { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalPineconeChatDataSourceParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalPineconeChatDataSourceParameters.cs deleted file mode 100644 index c886686b184b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalPineconeChatDataSourceParameters.cs +++ /dev/null @@ -1,160 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The PineconeChatDataSourceParameters. - internal partial class InternalPineconeChatDataSourceParameters - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - /// The environment name to use with Pinecone. - /// The name of the Pinecone database index to use. - /// - /// The authentication mechanism to use with Pinecone. - /// Supported authentication mechanisms for Pinecone include: API key. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// The vectorization source to use as an embedding dependency for the Pinecone data source. - /// Supported vectorization sources for Pinecone include: deployment name. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// Field mappings to apply to data used by the Pinecone data source. - /// Note that content field mappings are required for Pinecone. - /// - /// , , , or is null. - public InternalPineconeChatDataSourceParameters(string environment, string indexName, DataSourceAuthentication authentication, DataSourceVectorizer vectorizationSource, DataSourceFieldMappings fieldMappings) - { - Argument.AssertNotNull(environment, nameof(environment)); - Argument.AssertNotNull(indexName, nameof(indexName)); - Argument.AssertNotNull(authentication, nameof(authentication)); - Argument.AssertNotNull(vectorizationSource, nameof(vectorizationSource)); - Argument.AssertNotNull(fieldMappings, nameof(fieldMappings)); - - _internalIncludeContexts = new ChangeTrackingList(); - Environment = environment; - IndexName = indexName; - Authentication = authentication; - VectorizationSource = vectorizationSource; - FieldMappings = fieldMappings; - } - - /// Initializes a new instance of . - /// The configured number of documents to feature in the query. - /// Whether queries should be restricted to use of the indexed data. - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - /// - /// The output context properties to include on the response. - /// By default, citations and intent will be requested. - /// - /// The environment name to use with Pinecone. - /// The name of the Pinecone database index to use. - /// - /// The authentication mechanism to use with Pinecone. - /// Supported authentication mechanisms for Pinecone include: API key. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// The vectorization source to use as an embedding dependency for the Pinecone data source. - /// Supported vectorization sources for Pinecone include: deployment name. - /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.. - /// - /// - /// Field mappings to apply to data used by the Pinecone data source. - /// Note that content field mappings are required for Pinecone. - /// - /// Keeps track of any properties unknown to the library. - internal InternalPineconeChatDataSourceParameters(int? topNDocuments, bool? inScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList internalIncludeContexts, string environment, string indexName, DataSourceAuthentication authentication, DataSourceVectorizer vectorizationSource, DataSourceFieldMappings fieldMappings, IDictionary serializedAdditionalRawData) - { - TopNDocuments = topNDocuments; - InScope = inScope; - Strictness = strictness; - MaxSearchQueries = maxSearchQueries; - AllowPartialResult = allowPartialResult; - _internalIncludeContexts = internalIncludeContexts; - Environment = environment; - IndexName = indexName; - Authentication = authentication; - VectorizationSource = vectorizationSource; - FieldMappings = fieldMappings; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal InternalPineconeChatDataSourceParameters() - { - } - - /// The configured number of documents to feature in the query. - public int? TopNDocuments { get; set; } - /// Whether queries should be restricted to use of the indexed data. - public bool? InScope { get; set; } - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - public int? Strictness { get; set; } - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - public int? MaxSearchQueries { get; set; } - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - public bool? AllowPartialResult { get; set; } - /// The environment name to use with Pinecone. - internal string Environment { get; set; } - /// The name of the Pinecone database index to use. - internal string IndexName { get; set; } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSource.cs deleted file mode 100644 index 7b93d69910d6..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSource.cs +++ /dev/null @@ -1,26 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// Unknown version of AzureChatDataSource. - internal partial class InternalUnknownAzureChatDataSource : ChatDataSource - { - /// Initializes a new instance of . - /// The differentiating type identifier for the data source. - /// Keeps track of any properties unknown to the library. - internal InternalUnknownAzureChatDataSource(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - /// Initializes a new instance of for deserialization. - internal InternalUnknownAzureChatDataSource() - { - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceAuthenticationOptions.Serialization.cs deleted file mode 100644 index a852533c4a82..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,137 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalUnknownAzureChatDataSourceAuthenticationOptions : 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(DataSourceAuthentication)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - DataSourceAuthentication 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(DataSourceAuthentication)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataSourceAuthentication(document.RootElement, options); - } - - internal static InternalUnknownAzureChatDataSourceAuthenticationOptions DeserializeInternalUnknownAzureChatDataSourceAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalUnknownAzureChatDataSourceAuthenticationOptions(type, serializedAdditionalRawData); - } - - 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(DataSourceAuthentication)} does not support writing '{options.Format}' format."); - } - } - - DataSourceAuthentication 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 DeserializeDataSourceAuthentication(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataSourceAuthentication)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalUnknownAzureChatDataSourceAuthenticationOptions FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUnknownAzureChatDataSourceAuthenticationOptions(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceAuthenticationOptions.cs deleted file mode 100644 index 1833688883e8..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceAuthenticationOptions.cs +++ /dev/null @@ -1,26 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// Unknown version of AzureChatDataSourceAuthenticationOptions. - internal partial class InternalUnknownAzureChatDataSourceAuthenticationOptions : DataSourceAuthentication - { - /// Initializes a new instance of . - /// Discriminator. - /// Keeps track of any properties unknown to the library. - internal InternalUnknownAzureChatDataSourceAuthenticationOptions(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - /// Initializes a new instance of for deserialization. - internal InternalUnknownAzureChatDataSourceAuthenticationOptions() - { - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceVectorizationSource.Serialization.cs deleted file mode 100644 index ed6bccf0c5ad..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceVectorizationSource.Serialization.cs +++ /dev/null @@ -1,137 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalUnknownAzureChatDataSourceVectorizationSource : 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(DataSourceVectorizer)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - DataSourceVectorizer 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(DataSourceVectorizer)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataSourceVectorizer(document.RootElement, options); - } - - internal static InternalUnknownAzureChatDataSourceVectorizationSource DeserializeInternalUnknownAzureChatDataSourceVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string type = "Unknown"; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new InternalUnknownAzureChatDataSourceVectorizationSource(type, serializedAdditionalRawData); - } - - 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(DataSourceVectorizer)} does not support writing '{options.Format}' format."); - } - } - - DataSourceVectorizer 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 DeserializeDataSourceVectorizer(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataSourceVectorizer)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalUnknownAzureChatDataSourceVectorizationSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUnknownAzureChatDataSourceVectorizationSource(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceVectorizationSource.cs deleted file mode 100644 index 56560cf74c1f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSourceVectorizationSource.cs +++ /dev/null @@ -1,26 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// Unknown version of AzureChatDataSourceVectorizationSource. - internal partial class InternalUnknownAzureChatDataSourceVectorizationSource : DataSourceVectorizer - { - /// Initializes a new instance of . - /// The differentiating identifier for the concrete vectorization source. - /// Keeps track of any properties unknown to the library. - internal InternalUnknownAzureChatDataSourceVectorizationSource(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - - /// Initializes a new instance of for deserialization. - internal InternalUnknownAzureChatDataSourceVectorizationSource() - { - } - } -} - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatDataSource.Serialization.cs deleted file mode 100644 index f3101a5b54ed..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatDataSource.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - public partial class MongoDBChatDataSource : 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(MongoDBChatDataSource)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("parameters") != true) - { - writer.WritePropertyName("parameters"u8); - writer.WriteObjectValue(InternalParameters, options); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - MongoDBChatDataSource 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(MongoDBChatDataSource)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeMongoDBChatDataSource(document.RootElement, options); - } - - internal static MongoDBChatDataSource DeserializeMongoDBChatDataSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - InternalMongoDBChatDataSourceParameters parameters = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("parameters"u8)) - { - parameters = InternalMongoDBChatDataSourceParameters.DeserializeInternalMongoDBChatDataSourceParameters(property.Value, options); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new MongoDBChatDataSource(type, serializedAdditionalRawData, parameters); - } - - 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(MongoDBChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - MongoDBChatDataSource 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 DeserializeMongoDBChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(MongoDBChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new MongoDBChatDataSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeMongoDBChatDataSource(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatDataSource.cs deleted file mode 100644 index 9a483cc28639..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatDataSource.cs +++ /dev/null @@ -1,14 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The MongoDBChatDataSource. - public partial class MongoDBChatDataSource : ChatDataSource - { - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..5d23de217a68 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class MongoDBChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MongoDBChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("parameters"u8); + writer.WriteObjectValue(Parameters, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MongoDBChatExtensionConfiguration 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(MongoDBChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMongoDBChatExtensionConfiguration(document.RootElement, options); + } + + internal static MongoDBChatExtensionConfiguration DeserializeMongoDBChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MongoDBChatExtensionParameters parameters = default; + AzureChatExtensionType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("parameters"u8)) + { + parameters = MongoDBChatExtensionParameters.DeserializeMongoDBChatExtensionParameters(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MongoDBChatExtensionConfiguration(type, serializedAdditionalRawData, parameters); + } + + 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(MongoDBChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + MongoDBChatExtensionConfiguration 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 DeserializeMongoDBChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MongoDBChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new MongoDBChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMongoDBChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.cs new file mode 100644 index 000000000000..d83d67452853 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A specific representation of configurable options for a MongoDB chat extension configuration. + public partial class MongoDBChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// The parameters for the MongoDB chat extension. + /// is null. + public MongoDBChatExtensionConfiguration(MongoDBChatExtensionParameters parameters) + { + Argument.AssertNotNull(parameters, nameof(parameters)); + + Type = AzureChatExtensionType.MongoDB; + Parameters = parameters; + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + /// The parameters for the MongoDB chat extension. + internal MongoDBChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData, MongoDBChatExtensionParameters parameters) : base(type, serializedAdditionalRawData) + { + Parameters = parameters; + } + + /// Initializes a new instance of for deserialization. + internal MongoDBChatExtensionConfiguration() + { + } + + /// The parameters for the MongoDB chat extension. + public MongoDBChatExtensionParameters Parameters { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalMongoDBChatDataSourceParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.Serialization.cs similarity index 54% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/InternalMongoDBChatDataSourceParameters.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.Serialization.cs index b692f22a29c8..05a6fc5105fc 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalMongoDBChatDataSourceParameters.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.Serialization.cs @@ -1,109 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - internal partial class InternalMongoDBChatDataSourceParameters : IJsonModel + public partial class MongoDBChatExtensionParameters : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(InternalMongoDBChatDataSourceParameters)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(MongoDBChatExtensionParameters)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("top_n_documents") != true && Optional.IsDefined(TopNDocuments)) + if (Optional.IsDefined(DocumentCount)) { writer.WritePropertyName("top_n_documents"u8); - writer.WriteNumberValue(TopNDocuments.Value); + writer.WriteNumberValue(DocumentCount.Value); } - if (SerializedAdditionalRawData?.ContainsKey("in_scope") != true && Optional.IsDefined(InScope)) + if (Optional.IsDefined(ShouldRestrictResultScope)) { writer.WritePropertyName("in_scope"u8); - writer.WriteBooleanValue(InScope.Value); + writer.WriteBooleanValue(ShouldRestrictResultScope.Value); } - if (SerializedAdditionalRawData?.ContainsKey("strictness") != true && Optional.IsDefined(Strictness)) + if (Optional.IsDefined(Strictness)) { writer.WritePropertyName("strictness"u8); writer.WriteNumberValue(Strictness.Value); } - if (SerializedAdditionalRawData?.ContainsKey("max_search_queries") != true && Optional.IsDefined(MaxSearchQueries)) + if (Optional.IsDefined(MaxSearchQueries)) { writer.WritePropertyName("max_search_queries"u8); writer.WriteNumberValue(MaxSearchQueries.Value); } - if (SerializedAdditionalRawData?.ContainsKey("allow_partial_result") != true && Optional.IsDefined(AllowPartialResult)) + if (Optional.IsDefined(AllowPartialResult)) { writer.WritePropertyName("allow_partial_result"u8); writer.WriteBooleanValue(AllowPartialResult.Value); } - if (SerializedAdditionalRawData?.ContainsKey("include_contexts") != true && Optional.IsCollectionDefined(_internalIncludeContexts)) + if (Optional.IsCollectionDefined(IncludeContexts)) { writer.WritePropertyName("include_contexts"u8); writer.WriteStartArray(); - foreach (var item in _internalIncludeContexts) + foreach (var item in IncludeContexts) { - writer.WriteStringValue(item); + writer.WriteStringValue(item.ToString()); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("endpoint") != true) - { - writer.WritePropertyName("endpoint"u8); - writer.WriteStringValue(Endpoint); - } - if (SerializedAdditionalRawData?.ContainsKey("database_name") != true) - { - writer.WritePropertyName("database_name"u8); - writer.WriteStringValue(DatabaseName); - } - if (SerializedAdditionalRawData?.ContainsKey("collection_name") != true) - { - writer.WritePropertyName("collection_name"u8); - writer.WriteStringValue(CollectionName); - } - if (SerializedAdditionalRawData?.ContainsKey("app_name") != true) - { - writer.WritePropertyName("app_name"u8); - writer.WriteStringValue(AppName); - } - if (SerializedAdditionalRawData?.ContainsKey("index_name") != true) - { - writer.WritePropertyName("index_name"u8); - writer.WriteStringValue(IndexName); - } - if (SerializedAdditionalRawData?.ContainsKey("authentication") != true) + if (Optional.IsDefined(Authentication)) { writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); - } - if (SerializedAdditionalRawData?.ContainsKey("embedding_dependency") != true) - { - writer.WritePropertyName("embedding_dependency"u8); - writer.WriteObjectValue(EmbeddingDependency, options); + writer.WriteObjectValue(Authentication, options); } - if (SerializedAdditionalRawData?.ContainsKey("fields_mapping") != true) + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(Endpoint); + writer.WritePropertyName("collection_name"u8); + writer.WriteStringValue(CollectionName); + writer.WritePropertyName("database_name"u8); + writer.WriteStringValue(DatabaseName); + writer.WritePropertyName("app_name"u8); + writer.WriteStringValue(AppName); + writer.WritePropertyName("index_name"u8); + writer.WriteStringValue(IndexName); + writer.WritePropertyName("fields_mapping"u8); + writer.WriteObjectValue(FieldsMapping, options); + writer.WritePropertyName("embedding_dependency"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(EmbeddingDependency); +#else + using (JsonDocument document = JsonDocument.Parse(EmbeddingDependency)) { - writer.WritePropertyName("fields_mapping"u8); - writer.WriteObjectValue(FieldMappings, options); + JsonSerializer.Serialize(writer, document.RootElement); } - if (SerializedAdditionalRawData != null) +#endif + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -118,19 +105,19 @@ void IJsonModel.Write(Utf8JsonWriter wr writer.WriteEndObject(); } - InternalMongoDBChatDataSourceParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + MongoDBChatExtensionParameters 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(InternalMongoDBChatDataSourceParameters)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(MongoDBChatExtensionParameters)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalMongoDBChatDataSourceParameters(document.RootElement, options); + return DeserializeMongoDBChatExtensionParameters(document.RootElement, options); } - internal static InternalMongoDBChatDataSourceParameters DeserializeInternalMongoDBChatDataSourceParameters(JsonElement element, ModelReaderWriterOptions options = null) + internal static MongoDBChatExtensionParameters DeserializeMongoDBChatExtensionParameters(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -143,15 +130,15 @@ internal static InternalMongoDBChatDataSourceParameters DeserializeInternalMongo int? strictness = default; int? maxSearchQueries = default; bool? allowPartialResult = default; - IList includeContexts = default; + IList includeContexts = default; + OnYourDataUsernameAndPasswordAuthenticationOptions authentication = default; string endpoint = default; - string databaseName = default; string collectionName = default; + string databaseName = default; string appName = default; string indexName = default; - DataSourceAuthentication authentication = default; - DataSourceVectorizer embeddingDependency = default; - DataSourceFieldMappings fieldsMapping = default; + MongoDBChatExtensionParametersFieldsMapping fieldsMapping = default; + BinaryData embeddingDependency = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -207,22 +194,26 @@ internal static InternalMongoDBChatDataSourceParameters DeserializeInternalMongo { continue; } - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(item.GetString()); + array.Add(new OnYourDataContextProperty(item.GetString())); } includeContexts = array; continue; } - if (property.NameEquals("endpoint"u8)) + if (property.NameEquals("authentication"u8)) { - endpoint = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + authentication = OnYourDataUsernameAndPasswordAuthenticationOptions.DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(property.Value, options); continue; } - if (property.NameEquals("database_name"u8)) + if (property.NameEquals("endpoint"u8)) { - databaseName = property.Value.GetString(); + endpoint = property.Value.GetString(); continue; } if (property.NameEquals("collection_name"u8)) @@ -230,6 +221,11 @@ internal static InternalMongoDBChatDataSourceParameters DeserializeInternalMongo collectionName = property.Value.GetString(); continue; } + if (property.NameEquals("database_name"u8)) + { + databaseName = property.Value.GetString(); + continue; + } if (property.NameEquals("app_name"u8)) { appName = property.Value.GetString(); @@ -240,90 +236,85 @@ internal static InternalMongoDBChatDataSourceParameters DeserializeInternalMongo indexName = property.Value.GetString(); continue; } - if (property.NameEquals("authentication"u8)) + if (property.NameEquals("fields_mapping"u8)) { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(property.Value, options); + fieldsMapping = MongoDBChatExtensionParametersFieldsMapping.DeserializeMongoDBChatExtensionParametersFieldsMapping(property.Value, options); continue; } if (property.NameEquals("embedding_dependency"u8)) { - embeddingDependency = DataSourceVectorizer.DeserializeDataSourceVectorizer(property.Value, options); - continue; - } - if (property.NameEquals("fields_mapping"u8)) - { - fieldsMapping = DataSourceFieldMappings.DeserializeDataSourceFieldMappings(property.Value, options); + embeddingDependency = BinaryData.FromString(property.Value.GetRawText()); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new InternalMongoDBChatDataSourceParameters( + return new MongoDBChatExtensionParameters( topNDocuments, inScope, strictness, maxSearchQueries, allowPartialResult, - includeContexts ?? new ChangeTrackingList(), + includeContexts ?? new ChangeTrackingList(), + authentication, endpoint, - databaseName, collectionName, + databaseName, appName, indexName, - authentication, - embeddingDependency, fieldsMapping, + embeddingDependency, 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(InternalMongoDBChatDataSourceParameters)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(MongoDBChatExtensionParameters)} does not support writing '{options.Format}' format."); } } - InternalMongoDBChatDataSourceParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + MongoDBChatExtensionParameters 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 DeserializeInternalMongoDBChatDataSourceParameters(document.RootElement, options); + return DeserializeMongoDBChatExtensionParameters(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalMongoDBChatDataSourceParameters)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(MongoDBChatExtensionParameters)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalMongoDBChatDataSourceParameters FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static MongoDBChatExtensionParameters FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalMongoDBChatDataSourceParameters(document.RootElement); + return DeserializeMongoDBChatExtensionParameters(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.cs new file mode 100644 index 000000000000..2bcbfbd262e3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.cs @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Parameters for the MongoDB chat extension. The supported authentication types are AccessToken, SystemAssignedManagedIdentity and UserAssignedManagedIdentity. + public partial class MongoDBChatExtensionParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The endpoint name for MongoDB. + /// The collection name for MongoDB. + /// The database name for MongoDB. + /// The app name for MongoDB. + /// The name of the MongoDB index. + /// + /// Field mappings to apply to data used by the MongoDB data source. + /// Note that content and vector field mappings are required for MongoDB. + /// + /// The vectorization source to use with the MongoDB chat extension. + /// , , , , , or is null. + public MongoDBChatExtensionParameters(string endpoint, string collectionName, string databaseName, string appName, string indexName, MongoDBChatExtensionParametersFieldsMapping fieldsMapping, BinaryData embeddingDependency) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(collectionName, nameof(collectionName)); + Argument.AssertNotNull(databaseName, nameof(databaseName)); + Argument.AssertNotNull(appName, nameof(appName)); + Argument.AssertNotNull(indexName, nameof(indexName)); + Argument.AssertNotNull(fieldsMapping, nameof(fieldsMapping)); + Argument.AssertNotNull(embeddingDependency, nameof(embeddingDependency)); + + IncludeContexts = new ChangeTrackingList(); + Endpoint = endpoint; + CollectionName = collectionName; + DatabaseName = databaseName; + AppName = appName; + IndexName = indexName; + FieldsMapping = fieldsMapping; + EmbeddingDependency = embeddingDependency; + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// + /// The endpoint name for MongoDB. + /// The collection name for MongoDB. + /// The database name for MongoDB. + /// The app name for MongoDB. + /// The name of the MongoDB index. + /// + /// Field mappings to apply to data used by the MongoDB data source. + /// Note that content and vector field mappings are required for MongoDB. + /// + /// The vectorization source to use with the MongoDB chat extension. + /// Keeps track of any properties unknown to the library. + internal MongoDBChatExtensionParameters(int? documentCount, bool? shouldRestrictResultScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList includeContexts, OnYourDataUsernameAndPasswordAuthenticationOptions authentication, string endpoint, string collectionName, string databaseName, string appName, string indexName, MongoDBChatExtensionParametersFieldsMapping fieldsMapping, BinaryData embeddingDependency, IDictionary serializedAdditionalRawData) + { + DocumentCount = documentCount; + ShouldRestrictResultScope = shouldRestrictResultScope; + Strictness = strictness; + MaxSearchQueries = maxSearchQueries; + AllowPartialResult = allowPartialResult; + IncludeContexts = includeContexts; + Authentication = authentication; + Endpoint = endpoint; + CollectionName = collectionName; + DatabaseName = databaseName; + AppName = appName; + IndexName = indexName; + FieldsMapping = fieldsMapping; + EmbeddingDependency = embeddingDependency; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MongoDBChatExtensionParameters() + { + } + + /// The configured top number of documents to feature for the configured query. + public int? DocumentCount { get; set; } + /// Whether queries should be restricted to use of indexed data. + public bool? ShouldRestrictResultScope { get; set; } + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + public int? Strictness { get; set; } + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + public int? MaxSearchQueries { get; set; } + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + public bool? AllowPartialResult { get; set; } + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + public IList IncludeContexts { get; } + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// + public OnYourDataUsernameAndPasswordAuthenticationOptions Authentication { get; set; } + /// The endpoint name for MongoDB. + public string Endpoint { get; } + /// The collection name for MongoDB. + public string CollectionName { get; } + /// The database name for MongoDB. + public string DatabaseName { get; } + /// The app name for MongoDB. + public string AppName { get; } + /// The name of the MongoDB index. + public string IndexName { get; } + /// + /// Field mappings to apply to data used by the MongoDB data source. + /// Note that content and vector field mappings are required for MongoDB. + /// + public MongoDBChatExtensionParametersFieldsMapping FieldsMapping { get; } + /// + /// The vectorization source to use with the MongoDB chat extension. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData EmbeddingDependency { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.Serialization.cs new file mode 100644 index 000000000000..1fb604e70ae3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.Serialization.cs @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class MongoDBChatExtensionParametersFieldsMapping : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(MongoDBChatExtensionParametersFieldsMapping)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("content_fields"u8); + writer.WriteStartArray(); + foreach (var item in ContentFields) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("vector_fields"u8); + writer.WriteStartArray(); + foreach (var item in VectorFields) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(TitleField)) + { + writer.WritePropertyName("title_field"u8); + writer.WriteStringValue(TitleField); + } + if (Optional.IsDefined(UrlField)) + { + writer.WritePropertyName("url_field"u8); + writer.WriteStringValue(UrlField); + } + if (Optional.IsDefined(FilepathField)) + { + writer.WritePropertyName("filepath_field"u8); + writer.WriteStringValue(FilepathField); + } + if (Optional.IsDefined(ContentFieldsSeparator)) + { + writer.WritePropertyName("content_fields_separator"u8); + writer.WriteStringValue(ContentFieldsSeparator); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + MongoDBChatExtensionParametersFieldsMapping 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(MongoDBChatExtensionParametersFieldsMapping)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMongoDBChatExtensionParametersFieldsMapping(document.RootElement, options); + } + + internal static MongoDBChatExtensionParametersFieldsMapping DeserializeMongoDBChatExtensionParametersFieldsMapping(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList contentFields = default; + IList vectorFields = default; + string titleField = default; + string urlField = default; + string filepathField = default; + string contentFieldsSeparator = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content_fields"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + contentFields = array; + continue; + } + if (property.NameEquals("vector_fields"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorFields = array; + continue; + } + if (property.NameEquals("title_field"u8)) + { + titleField = property.Value.GetString(); + continue; + } + if (property.NameEquals("url_field"u8)) + { + urlField = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath_field"u8)) + { + filepathField = property.Value.GetString(); + continue; + } + if (property.NameEquals("content_fields_separator"u8)) + { + contentFieldsSeparator = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MongoDBChatExtensionParametersFieldsMapping( + contentFields, + vectorFields, + titleField, + urlField, + filepathField, + contentFieldsSeparator, + serializedAdditionalRawData); + } + + 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(MongoDBChatExtensionParametersFieldsMapping)} does not support writing '{options.Format}' format."); + } + } + + MongoDBChatExtensionParametersFieldsMapping 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 DeserializeMongoDBChatExtensionParametersFieldsMapping(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MongoDBChatExtensionParametersFieldsMapping)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MongoDBChatExtensionParametersFieldsMapping FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeMongoDBChatExtensionParametersFieldsMapping(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.cs new file mode 100644 index 000000000000..bfe79488c08c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The MongoDBChatExtensionParametersFieldsMapping. + public partial class MongoDBChatExtensionParametersFieldsMapping + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// + /// or is null. + public MongoDBChatExtensionParametersFieldsMapping(IEnumerable contentFields, IEnumerable vectorFields) + { + Argument.AssertNotNull(contentFields, nameof(contentFields)); + Argument.AssertNotNull(vectorFields, nameof(vectorFields)); + + ContentFields = contentFields.ToList(); + VectorFields = vectorFields.ToList(); + } + + /// Initializes a new instance of . + /// + /// + /// + /// + /// + /// + /// Keeps track of any properties unknown to the library. + internal MongoDBChatExtensionParametersFieldsMapping(IList contentFields, IList vectorFields, string titleField, string urlField, string filepathField, string contentFieldsSeparator, IDictionary serializedAdditionalRawData) + { + ContentFields = contentFields; + VectorFields = vectorFields; + TitleField = titleField; + UrlField = urlField; + FilepathField = filepathField; + ContentFieldsSeparator = contentFieldsSeparator; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MongoDBChatExtensionParametersFieldsMapping() + { + } + + /// Gets the content fields. + public IList ContentFields { get; } + /// Gets the vector fields. + public IList VectorFields { get; } + /// Gets or sets the title field. + public string TitleField { get; set; } + /// Gets or sets the url field. + public string UrlField { get; set; } + /// Gets or sets the filepath field. + public string FilepathField { get; set; } + /// Gets or sets the content fields separator. + public string ContentFieldsSeparator { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..a7e54c682a29 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataAccessTokenAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataAccessTokenAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("access_token"u8); + writer.WriteStringValue(AccessToken); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataAccessTokenAuthenticationOptions 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(OnYourDataAccessTokenAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataAccessTokenAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataAccessTokenAuthenticationOptions DeserializeOnYourDataAccessTokenAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string accessToken = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("access_token"u8)) + { + accessToken = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataAccessTokenAuthenticationOptions(type, serializedAdditionalRawData, accessToken); + } + + 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(OnYourDataAccessTokenAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataAccessTokenAuthenticationOptions 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 DeserializeOnYourDataAccessTokenAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataAccessTokenAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataAccessTokenAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataAccessTokenAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.cs new file mode 100644 index 000000000000..50ccaddc9fd2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using access token. + public partial class OnYourDataAccessTokenAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The access token to use for authentication. + /// is null. + public OnYourDataAccessTokenAuthenticationOptions(string accessToken) + { + Argument.AssertNotNull(accessToken, nameof(accessToken)); + + Type = OnYourDataAuthenticationType.AccessToken; + AccessToken = accessToken; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The access token to use for authentication. + internal OnYourDataAccessTokenAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string accessToken) : base(type, serializedAdditionalRawData) + { + AccessToken = accessToken; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataAccessTokenAuthenticationOptions() + { + } + + /// The access token to use for authentication. + public string AccessToken { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..cc6e44bb84fc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataApiKeyAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataApiKeyAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("key"u8); + writer.WriteStringValue(Key); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataApiKeyAuthenticationOptions 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(OnYourDataApiKeyAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataApiKeyAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataApiKeyAuthenticationOptions DeserializeOnYourDataApiKeyAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string key = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("key"u8)) + { + key = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataApiKeyAuthenticationOptions(type, serializedAdditionalRawData, key); + } + + 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(OnYourDataApiKeyAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataApiKeyAuthenticationOptions 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 DeserializeOnYourDataApiKeyAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataApiKeyAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataApiKeyAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataApiKeyAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.cs new file mode 100644 index 000000000000..f0a14f528a7c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using an API key. + public partial class OnYourDataApiKeyAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The API key to use for authentication. + /// is null. + public OnYourDataApiKeyAuthenticationOptions(string key) + { + Argument.AssertNotNull(key, nameof(key)); + + Type = OnYourDataAuthenticationType.ApiKey; + Key = key; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The API key to use for authentication. + internal OnYourDataApiKeyAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string key) : base(type, serializedAdditionalRawData) + { + Key = key; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataApiKeyAuthenticationOptions() + { + } + + /// The API key to use for authentication. + public string Key { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..272a87f93700 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.Serialization.cs @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownOnYourDataAuthenticationOptions))] + public partial class OnYourDataAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataAuthenticationOptions 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(OnYourDataAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataAuthenticationOptions DeserializeOnYourDataAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "access_token": return OnYourDataAccessTokenAuthenticationOptions.DeserializeOnYourDataAccessTokenAuthenticationOptions(element, options); + case "api_key": return OnYourDataApiKeyAuthenticationOptions.DeserializeOnYourDataApiKeyAuthenticationOptions(element, options); + case "connection_string": return OnYourDataConnectionStringAuthenticationOptions.DeserializeOnYourDataConnectionStringAuthenticationOptions(element, options); + case "encoded_api_key": return OnYourDataEncodedApiKeyAuthenticationOptions.DeserializeOnYourDataEncodedApiKeyAuthenticationOptions(element, options); + case "key_and_key_id": return OnYourDataKeyAndKeyIdAuthenticationOptions.DeserializeOnYourDataKeyAndKeyIdAuthenticationOptions(element, options); + case "system_assigned_managed_identity": return OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.DeserializeOnYourDataSystemAssignedManagedIdentityAuthenticationOptions(element, options); + case "user_assigned_managed_identity": return OnYourDataUserAssignedManagedIdentityAuthenticationOptions.DeserializeOnYourDataUserAssignedManagedIdentityAuthenticationOptions(element, options); + case "username_and_password": return OnYourDataUsernameAndPasswordAuthenticationOptions.DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(element, options); + } + } + return UnknownOnYourDataAuthenticationOptions.DeserializeUnknownOnYourDataAuthenticationOptions(element, 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(OnYourDataAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataAuthenticationOptions 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 DeserializeOnYourDataAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OnYourDataAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.cs new file mode 100644 index 000000000000..e507e2c7c801 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// The authentication options for Azure OpenAI On Your Data. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + public abstract partial class OnYourDataAuthenticationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected OnYourDataAuthenticationOptions() + { + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + internal OnYourDataAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The authentication type. + internal OnYourDataAuthenticationType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationType.cs new file mode 100644 index 000000000000..3505399d9f9d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationType.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The authentication types supported with Azure OpenAI On Your Data. + internal readonly partial struct OnYourDataAuthenticationType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OnYourDataAuthenticationType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ApiKeyValue = "api_key"; + private const string ConnectionStringValue = "connection_string"; + private const string KeyAndKeyIdValue = "key_and_key_id"; + private const string EncodedApiKeyValue = "encoded_api_key"; + private const string AccessTokenValue = "access_token"; + private const string SystemAssignedManagedIdentityValue = "system_assigned_managed_identity"; + private const string UserAssignedManagedIdentityValue = "user_assigned_managed_identity"; + private const string UsernameAndPasswordValue = "username_and_password"; + + /// Authentication via API key. + public static OnYourDataAuthenticationType ApiKey { get; } = new OnYourDataAuthenticationType(ApiKeyValue); + /// Authentication via connection string. + public static OnYourDataAuthenticationType ConnectionString { get; } = new OnYourDataAuthenticationType(ConnectionStringValue); + /// Authentication via key and key ID pair. + public static OnYourDataAuthenticationType KeyAndKeyId { get; } = new OnYourDataAuthenticationType(KeyAndKeyIdValue); + /// Authentication via encoded API key. + public static OnYourDataAuthenticationType EncodedApiKey { get; } = new OnYourDataAuthenticationType(EncodedApiKeyValue); + /// Authentication via access token. + public static OnYourDataAuthenticationType AccessToken { get; } = new OnYourDataAuthenticationType(AccessTokenValue); + /// Authentication via system-assigned managed identity. + public static OnYourDataAuthenticationType SystemAssignedManagedIdentity { get; } = new OnYourDataAuthenticationType(SystemAssignedManagedIdentityValue); + /// Authentication via user-assigned managed identity. + public static OnYourDataAuthenticationType UserAssignedManagedIdentity { get; } = new OnYourDataAuthenticationType(UserAssignedManagedIdentityValue); + /// Authentication via username and password. + public static OnYourDataAuthenticationType UsernameAndPassword { get; } = new OnYourDataAuthenticationType(UsernameAndPasswordValue); + /// Determines if two values are the same. + public static bool operator ==(OnYourDataAuthenticationType left, OnYourDataAuthenticationType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OnYourDataAuthenticationType left, OnYourDataAuthenticationType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OnYourDataAuthenticationType(string value) => new OnYourDataAuthenticationType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OnYourDataAuthenticationType other && Equals(other); + /// + public bool Equals(OnYourDataAuthenticationType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..07060a78b41b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataConnectionStringAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataConnectionStringAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("connection_string"u8); + writer.WriteStringValue(ConnectionString); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataConnectionStringAuthenticationOptions 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(OnYourDataConnectionStringAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataConnectionStringAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataConnectionStringAuthenticationOptions DeserializeOnYourDataConnectionStringAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string connectionString = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("connection_string"u8)) + { + connectionString = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataConnectionStringAuthenticationOptions(type, serializedAdditionalRawData, connectionString); + } + + 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(OnYourDataConnectionStringAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataConnectionStringAuthenticationOptions 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 DeserializeOnYourDataConnectionStringAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataConnectionStringAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataConnectionStringAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataConnectionStringAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.cs new file mode 100644 index 000000000000..a3a007891075 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using a connection string. + public partial class OnYourDataConnectionStringAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The connection string to use for authentication. + /// is null. + public OnYourDataConnectionStringAuthenticationOptions(string connectionString) + { + Argument.AssertNotNull(connectionString, nameof(connectionString)); + + Type = OnYourDataAuthenticationType.ConnectionString; + ConnectionString = connectionString; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The connection string to use for authentication. + internal OnYourDataConnectionStringAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string connectionString) : base(type, serializedAdditionalRawData) + { + ConnectionString = connectionString; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataConnectionStringAuthenticationOptions() + { + } + + /// The connection string to use for authentication. + public string ConnectionString { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataContextProperty.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataContextProperty.cs new file mode 100644 index 000000000000..741585547c4a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataContextProperty.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The context property. + public readonly partial struct OnYourDataContextProperty : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OnYourDataContextProperty(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string CitationsValue = "citations"; + private const string IntentValue = "intent"; + private const string AllRetrievedDocumentsValue = "all_retrieved_documents"; + + /// The `citations` property. + public static OnYourDataContextProperty Citations { get; } = new OnYourDataContextProperty(CitationsValue); + /// The `intent` property. + public static OnYourDataContextProperty Intent { get; } = new OnYourDataContextProperty(IntentValue); + /// The `all_retrieved_documents` property. + public static OnYourDataContextProperty AllRetrievedDocuments { get; } = new OnYourDataContextProperty(AllRetrievedDocumentsValue); + /// Determines if two values are the same. + public static bool operator ==(OnYourDataContextProperty left, OnYourDataContextProperty right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OnYourDataContextProperty left, OnYourDataContextProperty right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OnYourDataContextProperty(string value) => new OnYourDataContextProperty(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OnYourDataContextProperty other && Equals(other); + /// + public bool Equals(OnYourDataContextProperty other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..05a2fb03e7d6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataDeploymentNameVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataDeploymentNameVectorizationSource)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("deployment_name"u8); + writer.WriteStringValue(DeploymentName); + if (Optional.IsDefined(Dimensions)) + { + writer.WritePropertyName("dimensions"u8); + writer.WriteNumberValue(Dimensions.Value); + } + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataDeploymentNameVectorizationSource 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(OnYourDataDeploymentNameVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataDeploymentNameVectorizationSource(document.RootElement, options); + } + + internal static OnYourDataDeploymentNameVectorizationSource DeserializeOnYourDataDeploymentNameVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string deploymentName = default; + int? dimensions = default; + OnYourDataVectorizationSourceType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("deployment_name"u8)) + { + deploymentName = property.Value.GetString(); + continue; + } + if (property.NameEquals("dimensions"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + dimensions = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorizationSourceType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataDeploymentNameVectorizationSource(type, serializedAdditionalRawData, deploymentName, dimensions); + } + + 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(OnYourDataDeploymentNameVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataDeploymentNameVectorizationSource 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 DeserializeOnYourDataDeploymentNameVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataDeploymentNameVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataDeploymentNameVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataDeploymentNameVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.cs new file mode 100644 index 000000000000..1183ff66cbe4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based + /// on an internal embeddings model deployment name in the same Azure OpenAI resource. + /// + public partial class OnYourDataDeploymentNameVectorizationSource : OnYourDataVectorizationSource + { + /// Initializes a new instance of . + /// The embedding model deployment name within the same Azure OpenAI resource. This enables you to use vector search without Azure OpenAI api-key and without Azure OpenAI public network access. + /// is null. + public OnYourDataDeploymentNameVectorizationSource(string deploymentName) + { + Argument.AssertNotNull(deploymentName, nameof(deploymentName)); + + Type = OnYourDataVectorizationSourceType.DeploymentName; + DeploymentName = deploymentName; + } + + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + /// The embedding model deployment name within the same Azure OpenAI resource. This enables you to use vector search without Azure OpenAI api-key and without Azure OpenAI public network access. + /// The number of dimensions the embeddings should have. Only supported in `text-embedding-3` and later models. + internal OnYourDataDeploymentNameVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData, string deploymentName, int? dimensions) : base(type, serializedAdditionalRawData) + { + DeploymentName = deploymentName; + Dimensions = dimensions; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataDeploymentNameVectorizationSource() + { + } + + /// The embedding model deployment name within the same Azure OpenAI resource. This enables you to use vector search without Azure OpenAI api-key and without Azure OpenAI public network access. + public string DeploymentName { get; } + /// The number of dimensions the embeddings should have. Only supported in `text-embedding-3` and later models. + public int? Dimensions { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..e9457427c4ed --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataEncodedApiKeyAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataEncodedApiKeyAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("encoded_api_key"u8); + writer.WriteStringValue(EncodedApiKey); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataEncodedApiKeyAuthenticationOptions 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(OnYourDataEncodedApiKeyAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataEncodedApiKeyAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataEncodedApiKeyAuthenticationOptions DeserializeOnYourDataEncodedApiKeyAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string encodedApiKey = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("encoded_api_key"u8)) + { + encodedApiKey = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataEncodedApiKeyAuthenticationOptions(type, serializedAdditionalRawData, encodedApiKey); + } + + 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(OnYourDataEncodedApiKeyAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataEncodedApiKeyAuthenticationOptions 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 DeserializeOnYourDataEncodedApiKeyAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataEncodedApiKeyAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataEncodedApiKeyAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataEncodedApiKeyAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.cs new file mode 100644 index 000000000000..927e2e27e169 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using an Elasticsearch encoded API key. + public partial class OnYourDataEncodedApiKeyAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The encoded API key to use for authentication. + /// is null. + public OnYourDataEncodedApiKeyAuthenticationOptions(string encodedApiKey) + { + Argument.AssertNotNull(encodedApiKey, nameof(encodedApiKey)); + + Type = OnYourDataAuthenticationType.EncodedApiKey; + EncodedApiKey = encodedApiKey; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The encoded API key to use for authentication. + internal OnYourDataEncodedApiKeyAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string encodedApiKey) : base(type, serializedAdditionalRawData) + { + EncodedApiKey = encodedApiKey; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataEncodedApiKeyAuthenticationOptions() + { + } + + /// The encoded API key to use for authentication. + public string EncodedApiKey { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..8186ceb769ec --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataEndpointVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataEndpointVectorizationSource)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(Endpoint.AbsoluteUri); + writer.WritePropertyName("authentication"u8); + writer.WriteObjectValue(Authentication, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataEndpointVectorizationSource 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(OnYourDataEndpointVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataEndpointVectorizationSource(document.RootElement, options); + } + + internal static OnYourDataEndpointVectorizationSource DeserializeOnYourDataEndpointVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Uri endpoint = default; + OnYourDataVectorSearchAuthenticationOptions authentication = default; + OnYourDataVectorizationSourceType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("endpoint"u8)) + { + endpoint = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("authentication"u8)) + { + authentication = OnYourDataVectorSearchAuthenticationOptions.DeserializeOnYourDataVectorSearchAuthenticationOptions(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorizationSourceType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataEndpointVectorizationSource(type, serializedAdditionalRawData, endpoint, authentication); + } + + 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(OnYourDataEndpointVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataEndpointVectorizationSource 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 DeserializeOnYourDataEndpointVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataEndpointVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataEndpointVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataEndpointVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.cs new file mode 100644 index 000000000000..5ab4f3198354 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based + /// on a public Azure OpenAI endpoint call for embeddings. + /// + public partial class OnYourDataEndpointVectorizationSource : OnYourDataVectorizationSource + { + /// Initializes a new instance of . + /// Specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. The api-version query parameter is not allowed. + /// + /// Specifies the authentication options to use when retrieving embeddings from the specified endpoint. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// or is null. + public OnYourDataEndpointVectorizationSource(Uri endpoint, OnYourDataVectorSearchAuthenticationOptions authentication) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(authentication, nameof(authentication)); + + Type = OnYourDataVectorizationSourceType.Endpoint; + Endpoint = endpoint; + Authentication = authentication; + } + + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + /// Specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. The api-version query parameter is not allowed. + /// + /// Specifies the authentication options to use when retrieving embeddings from the specified endpoint. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + internal OnYourDataEndpointVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData, Uri endpoint, OnYourDataVectorSearchAuthenticationOptions authentication) : base(type, serializedAdditionalRawData) + { + Endpoint = endpoint; + Authentication = authentication; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataEndpointVectorizationSource() + { + } + + /// Specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. The api-version query parameter is not allowed. + public Uri Endpoint { get; } + /// + /// Specifies the authentication options to use when retrieving embeddings from the specified endpoint. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public OnYourDataVectorSearchAuthenticationOptions Authentication { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..89265a730aa7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataIntegratedVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataIntegratedVectorizationSource)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataIntegratedVectorizationSource 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(OnYourDataIntegratedVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataIntegratedVectorizationSource(document.RootElement, options); + } + + internal static OnYourDataIntegratedVectorizationSource DeserializeOnYourDataIntegratedVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OnYourDataVectorizationSourceType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorizationSourceType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataIntegratedVectorizationSource(type, serializedAdditionalRawData); + } + + 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(OnYourDataIntegratedVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataIntegratedVectorizationSource 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 DeserializeOnYourDataIntegratedVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataIntegratedVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataIntegratedVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataIntegratedVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.cs new file mode 100644 index 000000000000..89325cda307e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Represents the integrated vectorizer defined within the search resource. + public partial class OnYourDataIntegratedVectorizationSource : OnYourDataVectorizationSource + { + /// Initializes a new instance of . + public OnYourDataIntegratedVectorizationSource() + { + Type = OnYourDataVectorizationSourceType.Integrated; + } + + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + internal OnYourDataIntegratedVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..d6fe020442d7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataKeyAndKeyIdAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataKeyAndKeyIdAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("key"u8); + writer.WriteStringValue(Key); + writer.WritePropertyName("key_id"u8); + writer.WriteStringValue(KeyId); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataKeyAndKeyIdAuthenticationOptions 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(OnYourDataKeyAndKeyIdAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataKeyAndKeyIdAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataKeyAndKeyIdAuthenticationOptions DeserializeOnYourDataKeyAndKeyIdAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string key = default; + string keyId = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("key"u8)) + { + key = property.Value.GetString(); + continue; + } + if (property.NameEquals("key_id"u8)) + { + keyId = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataKeyAndKeyIdAuthenticationOptions(type, serializedAdditionalRawData, key, keyId); + } + + 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(OnYourDataKeyAndKeyIdAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataKeyAndKeyIdAuthenticationOptions 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 DeserializeOnYourDataKeyAndKeyIdAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataKeyAndKeyIdAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataKeyAndKeyIdAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataKeyAndKeyIdAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.cs new file mode 100644 index 000000000000..469ac62213b4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using an Elasticsearch key and key ID pair. + public partial class OnYourDataKeyAndKeyIdAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The key to use for authentication. + /// The key ID to use for authentication. + /// or is null. + public OnYourDataKeyAndKeyIdAuthenticationOptions(string key, string keyId) + { + Argument.AssertNotNull(key, nameof(key)); + Argument.AssertNotNull(keyId, nameof(keyId)); + + Type = OnYourDataAuthenticationType.KeyAndKeyId; + Key = key; + KeyId = keyId; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The key to use for authentication. + /// The key ID to use for authentication. + internal OnYourDataKeyAndKeyIdAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string key, string keyId) : base(type, serializedAdditionalRawData) + { + Key = key; + KeyId = keyId; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataKeyAndKeyIdAuthenticationOptions() + { + } + + /// The key to use for authentication. + public string Key { get; } + /// The key ID to use for authentication. + public string KeyId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..76c0a9955de5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataModelIdVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataModelIdVectorizationSource)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("model_id"u8); + writer.WriteStringValue(ModelId); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataModelIdVectorizationSource 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(OnYourDataModelIdVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataModelIdVectorizationSource(document.RootElement, options); + } + + internal static OnYourDataModelIdVectorizationSource DeserializeOnYourDataModelIdVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string modelId = default; + OnYourDataVectorizationSourceType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("model_id"u8)) + { + modelId = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorizationSourceType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataModelIdVectorizationSource(type, serializedAdditionalRawData, modelId); + } + + 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(OnYourDataModelIdVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataModelIdVectorizationSource 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 DeserializeOnYourDataModelIdVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataModelIdVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataModelIdVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataModelIdVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.cs new file mode 100644 index 000000000000..3db079445dbc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based + /// on a search service model ID. Currently only supported by Elasticsearch®. + /// + public partial class OnYourDataModelIdVectorizationSource : OnYourDataVectorizationSource + { + /// Initializes a new instance of . + /// The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. + /// is null. + public OnYourDataModelIdVectorizationSource(string modelId) + { + Argument.AssertNotNull(modelId, nameof(modelId)); + + Type = OnYourDataVectorizationSourceType.ModelId; + ModelId = modelId; + } + + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + /// The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. + internal OnYourDataModelIdVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData, string modelId) : base(type, serializedAdditionalRawData) + { + ModelId = modelId; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataModelIdVectorizationSource() + { + } + + /// The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. + public string ModelId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..a2321ebaf0d7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataSystemAssignedManagedIdentityAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataSystemAssignedManagedIdentityAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataSystemAssignedManagedIdentityAuthenticationOptions 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(OnYourDataSystemAssignedManagedIdentityAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataSystemAssignedManagedIdentityAuthenticationOptions DeserializeOnYourDataSystemAssignedManagedIdentityAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataSystemAssignedManagedIdentityAuthenticationOptions(type, serializedAdditionalRawData); + } + + 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(OnYourDataSystemAssignedManagedIdentityAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataSystemAssignedManagedIdentityAuthenticationOptions 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 DeserializeOnYourDataSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataSystemAssignedManagedIdentityAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataSystemAssignedManagedIdentityAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.cs new file mode 100644 index 000000000000..734ef7b5d70c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using a system-assigned managed identity. + public partial class OnYourDataSystemAssignedManagedIdentityAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + public OnYourDataSystemAssignedManagedIdentityAuthenticationOptions() + { + Type = OnYourDataAuthenticationType.SystemAssignedManagedIdentity; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + internal OnYourDataSystemAssignedManagedIdentityAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..85f6f9d26e4a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataUserAssignedManagedIdentityAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataUserAssignedManagedIdentityAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("managed_identity_resource_id"u8); + writer.WriteStringValue(ManagedIdentityResourceId); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataUserAssignedManagedIdentityAuthenticationOptions 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(OnYourDataUserAssignedManagedIdentityAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataUserAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataUserAssignedManagedIdentityAuthenticationOptions DeserializeOnYourDataUserAssignedManagedIdentityAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string managedIdentityResourceId = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("managed_identity_resource_id"u8)) + { + managedIdentityResourceId = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataUserAssignedManagedIdentityAuthenticationOptions(type, serializedAdditionalRawData, managedIdentityResourceId); + } + + 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(OnYourDataUserAssignedManagedIdentityAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataUserAssignedManagedIdentityAuthenticationOptions 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 DeserializeOnYourDataUserAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataUserAssignedManagedIdentityAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataUserAssignedManagedIdentityAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataUserAssignedManagedIdentityAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.cs new file mode 100644 index 000000000000..89ca44bf1441 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using a user-assigned managed identity. + public partial class OnYourDataUserAssignedManagedIdentityAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The resource ID of the user-assigned managed identity to use for authentication. + /// is null. + public OnYourDataUserAssignedManagedIdentityAuthenticationOptions(string managedIdentityResourceId) + { + Argument.AssertNotNull(managedIdentityResourceId, nameof(managedIdentityResourceId)); + + Type = OnYourDataAuthenticationType.UserAssignedManagedIdentity; + ManagedIdentityResourceId = managedIdentityResourceId; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The resource ID of the user-assigned managed identity to use for authentication. + internal OnYourDataUserAssignedManagedIdentityAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string managedIdentityResourceId) : base(type, serializedAdditionalRawData) + { + ManagedIdentityResourceId = managedIdentityResourceId; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataUserAssignedManagedIdentityAuthenticationOptions() + { + } + + /// The resource ID of the user-assigned managed identity to use for authentication. + public string ManagedIdentityResourceId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..1c30927617ad --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataUsernameAndPasswordAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataUsernameAndPasswordAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("username"u8); + writer.WriteStringValue(Username); + writer.WritePropertyName("password"u8); + writer.WriteStringValue(Password); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataUsernameAndPasswordAuthenticationOptions 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(OnYourDataUsernameAndPasswordAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataUsernameAndPasswordAuthenticationOptions DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string username = default; + string password = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("username"u8)) + { + username = property.Value.GetString(); + continue; + } + if (property.NameEquals("password"u8)) + { + password = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataUsernameAndPasswordAuthenticationOptions(type, serializedAdditionalRawData, username, password); + } + + 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(OnYourDataUsernameAndPasswordAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataUsernameAndPasswordAuthenticationOptions 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 DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataUsernameAndPasswordAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataUsernameAndPasswordAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.cs new file mode 100644 index 000000000000..3b382f621f00 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using a username and password. + public partial class OnYourDataUsernameAndPasswordAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The username. + /// The password. + /// or is null. + public OnYourDataUsernameAndPasswordAuthenticationOptions(string username, string password) + { + Argument.AssertNotNull(username, nameof(username)); + Argument.AssertNotNull(password, nameof(password)); + + Type = OnYourDataAuthenticationType.UsernameAndPassword; + Username = username; + Password = password; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The username. + /// The password. + internal OnYourDataUsernameAndPasswordAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string username, string password) : base(type, serializedAdditionalRawData) + { + Username = username; + Password = password; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataUsernameAndPasswordAuthenticationOptions() + { + } + + /// The username. + public string Username { get; } + /// The password. + public string Password { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceApiKeyAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.Serialization.cs similarity index 51% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceApiKeyAuthenticationOptions.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.Serialization.cs index 4d448e27cf9e..28a9b7be8b8d 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalAzureChatDataSourceApiKeyAuthenticationOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.Serialization.cs @@ -1,44 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - internal partial class InternalAzureChatDataSourceApiKeyAuthenticationOptions : IJsonModel + public partial class OnYourDataVectorSearchAccessTokenAuthenticationOptions : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(InternalAzureChatDataSourceApiKeyAuthenticationOptions)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAccessTokenAuthenticationOptions)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("key") != true) + writer.WritePropertyName("access_token"u8); + writer.WriteStringValue(AccessToken); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) { - writer.WritePropertyName("key"u8); - writer.WriteStringValue(Key); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -53,19 +48,19 @@ void IJsonModel.Write(Ut writer.WriteEndObject(); } - InternalAzureChatDataSourceApiKeyAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OnYourDataVectorSearchAccessTokenAuthenticationOptions 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(InternalAzureChatDataSourceApiKeyAuthenticationOptions)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAccessTokenAuthenticationOptions)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceApiKeyAuthenticationOptions(document.RootElement, options); + return DeserializeOnYourDataVectorSearchAccessTokenAuthenticationOptions(document.RootElement, options); } - internal static InternalAzureChatDataSourceApiKeyAuthenticationOptions DeserializeInternalAzureChatDataSourceApiKeyAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + internal static OnYourDataVectorSearchAccessTokenAuthenticationOptions DeserializeOnYourDataVectorSearchAccessTokenAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -73,76 +68,76 @@ internal static InternalAzureChatDataSourceApiKeyAuthenticationOptions Deseriali { return null; } - string key = default; - string type = default; + string accessToken = default; + OnYourDataVectorSearchAuthenticationType type = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("key"u8)) + if (property.NameEquals("access_token"u8)) { - key = property.Value.GetString(); + accessToken = property.Value.GetString(); continue; } if (property.NameEquals("type"u8)) { - type = property.Value.GetString(); + type = new OnYourDataVectorSearchAuthenticationType(property.Value.GetString()); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new InternalAzureChatDataSourceApiKeyAuthenticationOptions(type, serializedAdditionalRawData, key); + return new OnYourDataVectorSearchAccessTokenAuthenticationOptions(type, serializedAdditionalRawData, accessToken); } - 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(InternalAzureChatDataSourceApiKeyAuthenticationOptions)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAccessTokenAuthenticationOptions)} does not support writing '{options.Format}' format."); } } - InternalAzureChatDataSourceApiKeyAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + OnYourDataVectorSearchAccessTokenAuthenticationOptions 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 DeserializeInternalAzureChatDataSourceApiKeyAuthenticationOptions(document.RootElement, options); + return DeserializeOnYourDataVectorSearchAccessTokenAuthenticationOptions(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceApiKeyAuthenticationOptions)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAccessTokenAuthenticationOptions)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalAzureChatDataSourceApiKeyAuthenticationOptions FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static new OnYourDataVectorSearchAccessTokenAuthenticationOptions FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceApiKeyAuthenticationOptions(document.RootElement); + return DeserializeOnYourDataVectorSearchAccessTokenAuthenticationOptions(document.RootElement); } - /// Convert into a . - internal override BinaryContent ToBinaryContent() + /// Convert into a . + internal override RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.cs new file mode 100644 index 000000000000..9a6cc8cd23c1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data vector search when using access token. + public partial class OnYourDataVectorSearchAccessTokenAuthenticationOptions : OnYourDataVectorSearchAuthenticationOptions + { + /// Initializes a new instance of . + /// The access token to use for authentication. + /// is null. + public OnYourDataVectorSearchAccessTokenAuthenticationOptions(string accessToken) + { + Argument.AssertNotNull(accessToken, nameof(accessToken)); + + Type = OnYourDataVectorSearchAuthenticationType.AccessToken; + AccessToken = accessToken; + } + + /// Initializes a new instance of . + /// The type of authentication to use. + /// Keeps track of any properties unknown to the library. + /// The access token to use for authentication. + internal OnYourDataVectorSearchAccessTokenAuthenticationOptions(OnYourDataVectorSearchAuthenticationType type, IDictionary serializedAdditionalRawData, string accessToken) : base(type, serializedAdditionalRawData) + { + AccessToken = accessToken; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataVectorSearchAccessTokenAuthenticationOptions() + { + } + + /// The access token to use for authentication. + public string AccessToken { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..d39da87bc40a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataVectorSearchApiKeyAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataVectorSearchApiKeyAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("key"u8); + writer.WriteStringValue(Key); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataVectorSearchApiKeyAuthenticationOptions 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(OnYourDataVectorSearchApiKeyAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorSearchApiKeyAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataVectorSearchApiKeyAuthenticationOptions DeserializeOnYourDataVectorSearchApiKeyAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string key = default; + OnYourDataVectorSearchAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("key"u8)) + { + key = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorSearchAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataVectorSearchApiKeyAuthenticationOptions(type, serializedAdditionalRawData, key); + } + + 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(OnYourDataVectorSearchApiKeyAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorSearchApiKeyAuthenticationOptions 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 DeserializeOnYourDataVectorSearchApiKeyAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchApiKeyAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataVectorSearchApiKeyAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataVectorSearchApiKeyAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.cs new file mode 100644 index 000000000000..6cb88743fc8a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using an API key. + public partial class OnYourDataVectorSearchApiKeyAuthenticationOptions : OnYourDataVectorSearchAuthenticationOptions + { + /// Initializes a new instance of . + /// The API key to use for authentication. + /// is null. + public OnYourDataVectorSearchApiKeyAuthenticationOptions(string key) + { + Argument.AssertNotNull(key, nameof(key)); + + Type = OnYourDataVectorSearchAuthenticationType.ApiKey; + Key = key; + } + + /// Initializes a new instance of . + /// The type of authentication to use. + /// Keeps track of any properties unknown to the library. + /// The API key to use for authentication. + internal OnYourDataVectorSearchApiKeyAuthenticationOptions(OnYourDataVectorSearchAuthenticationType type, IDictionary serializedAdditionalRawData, string key) : base(type, serializedAdditionalRawData) + { + Key = key; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataVectorSearchApiKeyAuthenticationOptions() + { + } + + /// The API key to use for authentication. + public string Key { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..6803f88cfd66 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.Serialization.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownOnYourDataVectorSearchAuthenticationOptions))] + public partial class OnYourDataVectorSearchAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataVectorSearchAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataVectorSearchAuthenticationOptions 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(OnYourDataVectorSearchAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorSearchAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataVectorSearchAuthenticationOptions DeserializeOnYourDataVectorSearchAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "access_token": return OnYourDataVectorSearchAccessTokenAuthenticationOptions.DeserializeOnYourDataVectorSearchAccessTokenAuthenticationOptions(element, options); + case "api_key": return OnYourDataVectorSearchApiKeyAuthenticationOptions.DeserializeOnYourDataVectorSearchApiKeyAuthenticationOptions(element, options); + } + } + return UnknownOnYourDataVectorSearchAuthenticationOptions.DeserializeUnknownOnYourDataVectorSearchAuthenticationOptions(element, 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(OnYourDataVectorSearchAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorSearchAuthenticationOptions 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 DeserializeOnYourDataVectorSearchAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OnYourDataVectorSearchAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataVectorSearchAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.cs new file mode 100644 index 000000000000..077fa22c2793 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// The authentication options for Azure OpenAI On Your Data vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class OnYourDataVectorSearchAuthenticationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected OnYourDataVectorSearchAuthenticationOptions() + { + } + + /// Initializes a new instance of . + /// The type of authentication to use. + /// Keeps track of any properties unknown to the library. + internal OnYourDataVectorSearchAuthenticationOptions(OnYourDataVectorSearchAuthenticationType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The type of authentication to use. + internal OnYourDataVectorSearchAuthenticationType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationType.cs new file mode 100644 index 000000000000..5b91b4f56ba1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The authentication types supported with Azure OpenAI On Your Data vector search. + internal readonly partial struct OnYourDataVectorSearchAuthenticationType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OnYourDataVectorSearchAuthenticationType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ApiKeyValue = "api_key"; + private const string AccessTokenValue = "access_token"; + + /// Authentication via API key. + public static OnYourDataVectorSearchAuthenticationType ApiKey { get; } = new OnYourDataVectorSearchAuthenticationType(ApiKeyValue); + /// Authentication via access token. + public static OnYourDataVectorSearchAuthenticationType AccessToken { get; } = new OnYourDataVectorSearchAuthenticationType(AccessTokenValue); + /// Determines if two values are the same. + public static bool operator ==(OnYourDataVectorSearchAuthenticationType left, OnYourDataVectorSearchAuthenticationType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OnYourDataVectorSearchAuthenticationType left, OnYourDataVectorSearchAuthenticationType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OnYourDataVectorSearchAuthenticationType(string value) => new OnYourDataVectorSearchAuthenticationType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OnYourDataVectorSearchAuthenticationType other && Equals(other); + /// + public bool Equals(OnYourDataVectorSearchAuthenticationType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..d5ae57970b3c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.Serialization.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownOnYourDataVectorizationSource))] + public partial class OnYourDataVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataVectorizationSource)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataVectorizationSource 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(OnYourDataVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorizationSource(document.RootElement, options); + } + + internal static OnYourDataVectorizationSource DeserializeOnYourDataVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "deployment_name": return OnYourDataDeploymentNameVectorizationSource.DeserializeOnYourDataDeploymentNameVectorizationSource(element, options); + case "endpoint": return OnYourDataEndpointVectorizationSource.DeserializeOnYourDataEndpointVectorizationSource(element, options); + case "integrated": return OnYourDataIntegratedVectorizationSource.DeserializeOnYourDataIntegratedVectorizationSource(element, options); + case "model_id": return OnYourDataModelIdVectorizationSource.DeserializeOnYourDataModelIdVectorizationSource(element, options); + } + } + return UnknownOnYourDataVectorizationSource.DeserializeUnknownOnYourDataVectorizationSource(element, 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(OnYourDataVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorizationSource 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 DeserializeOnYourDataVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OnYourDataVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOnYourDataVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.cs new file mode 100644 index 000000000000..c675da983dd8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a vectorization source for Azure OpenAI On Your Data with vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public abstract partial class OnYourDataVectorizationSource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected OnYourDataVectorizationSource() + { + } + + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + internal OnYourDataVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The type of vectorization source to use. + internal OnYourDataVectorizationSourceType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSourceType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSourceType.cs new file mode 100644 index 000000000000..1f951716f33e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSourceType.cs @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// + /// Represents the available sources Azure OpenAI On Your Data can use to configure vectorization of data for use with + /// vector search. + /// + internal readonly partial struct OnYourDataVectorizationSourceType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OnYourDataVectorizationSourceType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EndpointValue = "endpoint"; + private const string DeploymentNameValue = "deployment_name"; + private const string ModelIdValue = "model_id"; + private const string IntegratedValue = "integrated"; + + /// Represents vectorization performed by public service calls to an Azure OpenAI embedding model. + public static OnYourDataVectorizationSourceType Endpoint { get; } = new OnYourDataVectorizationSourceType(EndpointValue); + /// + /// Represents an Ada model deployment name to use. This model deployment must be in the same Azure OpenAI resource, but + /// On Your Data will use this model deployment via an internal call rather than a public one, which enables vector + /// search even in private networks. + /// + public static OnYourDataVectorizationSourceType DeploymentName { get; } = new OnYourDataVectorizationSourceType(DeploymentNameValue); + /// + /// Represents a specific embedding model ID as defined in the search service. + /// Currently only supported by Elasticsearch®. + /// + public static OnYourDataVectorizationSourceType ModelId { get; } = new OnYourDataVectorizationSourceType(ModelIdValue); + /// Represents the integrated vectorizer defined within the search resource. + public static OnYourDataVectorizationSourceType Integrated { get; } = new OnYourDataVectorizationSourceType(IntegratedValue); + /// Determines if two values are the same. + public static bool operator ==(OnYourDataVectorizationSourceType left, OnYourDataVectorizationSourceType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OnYourDataVectorizationSourceType left, OnYourDataVectorizationSourceType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OnYourDataVectorizationSourceType(string value) => new OnYourDataVectorizationSourceType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OnYourDataVectorizationSourceType other && Equals(other); + /// + public bool Equals(OnYourDataVectorizationSourceType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClient.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClient.cs new file mode 100644 index 000000000000..eb3ffa08498c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClient.cs @@ -0,0 +1,2867 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.OpenAI +{ + // Data plane generated client. + /// The OpenAI service client. + public partial class OpenAIClient + { + private const string AuthorizationHeader = "api-key"; + private readonly AzureKeyCredential _keyCredential; + private static readonly string[] AuthorizationScopes = new string[] { "https://cognitiveservices.azure.com/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of OpenAIClient for mocking. + protected OpenAIClient() + { + } + + /// Initializes a new instance of OpenAIClient. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + /// A credential used to authenticate to an Azure Service. + /// or is null. + public OpenAIClient(Uri endpoint, AzureKeyCredential credential) : this(endpoint, credential, new OpenAIClientOptions()) + { + } + + /// Initializes a new instance of OpenAIClient. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + /// A credential used to authenticate to an Azure Service. + /// or is null. + public OpenAIClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new OpenAIClientOptions()) + { + } + + /// Initializes a new instance of OpenAIClient. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public OpenAIClient(Uri endpoint, AzureKeyCredential credential, OpenAIClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new OpenAIClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _keyCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new AzureKeyCredentialPolicy(_keyCredential, AuthorizationHeader) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// Initializes a new instance of OpenAIClient. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public OpenAIClient(Uri endpoint, TokenCredential credential, OpenAIClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new OpenAIClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// + /// Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + /// written language corresponding to the language it was spoken in. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio transcription request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetAudioTranscriptionAsPlainTextAsync(string deploymentId, AudioTranscriptionOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetAudioTranscriptionAsPlainTextAsync(deploymentId, content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(response.Content.ToString(), response); + } + + /// + /// Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + /// written language corresponding to the language it was spoken in. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio transcription request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetAudioTranscriptionAsPlainText(string deploymentId, AudioTranscriptionOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetAudioTranscriptionAsPlainText(deploymentId, content, content.ContentType, context); + return Response.FromValue(response.Content.ToString(), response); + } + + /// + /// [Protocol Method] Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + /// written language corresponding to the language it was spoken in. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetAudioTranscriptionAsPlainTextAsync(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranscriptionAsPlainText"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranscriptionAsPlainTextRequest(deploymentId, content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + /// written language corresponding to the language it was spoken in. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetAudioTranscriptionAsPlainText(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranscriptionAsPlainText"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranscriptionAsPlainTextRequest(deploymentId, content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + /// written language corresponding to the language it was spoken in. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio transcription request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetAudioTranscriptionAsResponseObjectAsync(string deploymentId, AudioTranscriptionOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetAudioTranscriptionAsResponseObjectAsync(deploymentId, content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(AudioTranscription.FromResponse(response), response); + } + + /// + /// Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + /// written language corresponding to the language it was spoken in. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio transcription request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetAudioTranscriptionAsResponseObject(string deploymentId, AudioTranscriptionOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetAudioTranscriptionAsResponseObject(deploymentId, content, content.ContentType, context); + return Response.FromValue(AudioTranscription.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + /// written language corresponding to the language it was spoken in. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetAudioTranscriptionAsResponseObjectAsync(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranscriptionAsResponseObject"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranscriptionAsResponseObjectRequest(deploymentId, content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + /// written language corresponding to the language it was spoken in. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetAudioTranscriptionAsResponseObject(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranscriptionAsResponseObject"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranscriptionAsResponseObjectRequest(deploymentId, content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets English language transcribed text and associated metadata from provided spoken audio data. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio translation request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetAudioTranslationAsPlainTextAsync(string deploymentId, AudioTranslationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetAudioTranslationAsPlainTextAsync(deploymentId, content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(response.Content.ToString(), response); + } + + /// Gets English language transcribed text and associated metadata from provided spoken audio data. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio translation request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetAudioTranslationAsPlainText(string deploymentId, AudioTranslationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetAudioTranslationAsPlainText(deploymentId, content, content.ContentType, context); + return Response.FromValue(response.Content.ToString(), response); + } + + /// + /// [Protocol Method] Gets English language transcribed text and associated metadata from provided spoken audio data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetAudioTranslationAsPlainTextAsync(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranslationAsPlainText"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranslationAsPlainTextRequest(deploymentId, content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets English language transcribed text and associated metadata from provided spoken audio data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetAudioTranslationAsPlainText(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranslationAsPlainText"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranslationAsPlainTextRequest(deploymentId, content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets English language transcribed text and associated metadata from provided spoken audio data. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio translation request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetAudioTranslationAsResponseObjectAsync(string deploymentId, AudioTranslationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetAudioTranslationAsResponseObjectAsync(deploymentId, content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(AudioTranslation.FromResponse(response), response); + } + + /// Gets English language transcribed text and associated metadata from provided spoken audio data. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio translation request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetAudioTranslationAsResponseObject(string deploymentId, AudioTranslationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetAudioTranslationAsResponseObject(deploymentId, content, content.ContentType, context); + return Response.FromValue(AudioTranslation.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets English language transcribed text and associated metadata from provided spoken audio data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetAudioTranslationAsResponseObjectAsync(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranslationAsResponseObject"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranslationAsResponseObjectRequest(deploymentId, content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets English language transcribed text and associated metadata from provided spoken audio data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetAudioTranslationAsResponseObject(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranslationAsResponseObject"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranslationAsResponseObjectRequest(deploymentId, content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Gets completions for the provided input prompts. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// The configuration information for a completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetCompletionsAsync(string deploymentId, CompletionsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetCompletionsAsync(deploymentId, content, context).ConfigureAwait(false); + return Response.FromValue(Completions.FromResponse(response), response); + } + + /// + /// Gets completions for the provided input prompts. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// The configuration information for a completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetCompletions(string deploymentId, CompletionsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetCompletions(deploymentId, content, context); + return Response.FromValue(Completions.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets completions for the provided input prompts. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetCompletionsAsync(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetCompletions"); + scope.Start(); + try + { + using HttpMessage message = CreateGetCompletionsRequest(deploymentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets completions for the provided input prompts. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetCompletions(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetCompletions"); + scope.Start(); + try + { + using HttpMessage message = CreateGetCompletionsRequest(deploymentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Gets chat completions for the provided chat messages. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// The configuration information for a chat completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetChatCompletionsAsync(string deploymentId, ChatCompletionsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetChatCompletionsAsync(deploymentId, content, context).ConfigureAwait(false); + return Response.FromValue(ChatCompletions.FromResponse(response), response); + } + + /// + /// Gets chat completions for the provided chat messages. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// The configuration information for a chat completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetChatCompletions(string deploymentId, ChatCompletionsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetChatCompletions(deploymentId, content, context); + return Response.FromValue(ChatCompletions.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets chat completions for the provided chat messages. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetChatCompletionsAsync(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetChatCompletions"); + scope.Start(); + try + { + using HttpMessage message = CreateGetChatCompletionsRequest(deploymentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets chat completions for the provided chat messages. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetChatCompletions(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetChatCompletions"); + scope.Start(); + try + { + using HttpMessage message = CreateGetChatCompletionsRequest(deploymentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Creates an image given a prompt. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// Represents the request data used to generate images. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetImageGenerationsAsync(string deploymentId, ImageGenerationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetImageGenerationsAsync(deploymentId, content, context).ConfigureAwait(false); + return Response.FromValue(ImageGenerations.FromResponse(response), response); + } + + /// Creates an image given a prompt. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// Represents the request data used to generate images. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetImageGenerations(string deploymentId, ImageGenerationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetImageGenerations(deploymentId, content, context); + return Response.FromValue(ImageGenerations.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates an image given a prompt. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetImageGenerationsAsync(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetImageGenerations"); + scope.Start(); + try + { + using HttpMessage message = CreateGetImageGenerationsRequest(deploymentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates an image given a prompt. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetImageGenerations(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetImageGenerations"); + scope.Start(); + try + { + using HttpMessage message = CreateGetImageGenerationsRequest(deploymentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Generates text-to-speech audio from the input text. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// A representation of the request options that control the behavior of a text-to-speech operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GenerateSpeechFromTextAsync(string deploymentId, SpeechGenerationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GenerateSpeechFromTextAsync(deploymentId, content, context).ConfigureAwait(false); + return Response.FromValue(response.Content, response); + } + + /// Generates text-to-speech audio from the input text. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// A representation of the request options that control the behavior of a text-to-speech operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GenerateSpeechFromText(string deploymentId, SpeechGenerationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GenerateSpeechFromText(deploymentId, content, context); + return Response.FromValue(response.Content, response); + } + + /// + /// [Protocol Method] Generates text-to-speech audio from the input text. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GenerateSpeechFromTextAsync(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GenerateSpeechFromText"); + scope.Start(); + try + { + using HttpMessage message = CreateGenerateSpeechFromTextRequest(deploymentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Generates text-to-speech audio from the input text. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GenerateSpeechFromText(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GenerateSpeechFromText"); + scope.Start(); + try + { + using HttpMessage message = CreateGenerateSpeechFromTextRequest(deploymentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Return the embeddings for a given prompt. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// The configuration information for an embeddings request. + /// Embeddings measure the relatedness of text strings and are commonly used for search, clustering, + /// recommendations, and other similar scenarios. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetEmbeddingsAsync(string deploymentId, EmbeddingsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetEmbeddingsAsync(deploymentId, content, context).ConfigureAwait(false); + return Response.FromValue(OpenAI.Embeddings.FromResponse(response), response); + } + + /// Return the embeddings for a given prompt. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// The configuration information for an embeddings request. + /// Embeddings measure the relatedness of text strings and are commonly used for search, clustering, + /// recommendations, and other similar scenarios. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetEmbeddings(string deploymentId, EmbeddingsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetEmbeddings(deploymentId, content, context); + return Response.FromValue(OpenAI.Embeddings.FromResponse(response), response); + } + + /// + /// [Protocol Method] Return the embeddings for a given prompt. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetEmbeddingsAsync(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetEmbeddings"); + scope.Start(); + try + { + using HttpMessage message = CreateGetEmbeddingsRequest(deploymentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Return the embeddings for a given prompt. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetEmbeddings(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetEmbeddings"); + scope.Start(); + try + { + using HttpMessage message = CreateGetEmbeddingsRequest(deploymentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets a list of previously uploaded files. + /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// The cancellation token to use. + public virtual async Task> GetFilesAsync(FilePurpose? purpose = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetFilesAsync(purpose?.ToString(), context).ConfigureAwait(false); + return Response.FromValue(FileListResponse.FromResponse(response), response); + } + + /// Gets a list of previously uploaded files. + /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// The cancellation token to use. + public virtual Response GetFiles(FilePurpose? purpose = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetFiles(purpose?.ToString(), context); + return Response.FromValue(FileListResponse.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets a list of previously uploaded files. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output" | "batch" | "batch_output" | "vision". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetFilesAsync(string purpose, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFiles"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFilesRequest(purpose, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a list of previously uploaded files. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output" | "batch" | "batch_output" | "vision". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetFiles(string purpose, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFiles"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFilesRequest(purpose, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Uploads a file for use by other operations. + /// The file data (not filename) to upload. + /// The intended purpose of the file. + /// A filename to associate with the uploaded data. + /// The cancellation token to use. + /// is null. + public virtual async Task> UploadFileAsync(Stream data, FilePurpose purpose, string filename = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + UploadFileRequest uploadFileRequest = new UploadFileRequest(data, purpose, filename, null); + using MultipartFormDataRequestContent content = uploadFileRequest.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await UploadFileAsync(content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// Uploads a file for use by other operations. + /// The file data (not filename) to upload. + /// The intended purpose of the file. + /// A filename to associate with the uploaded data. + /// The cancellation token to use. + /// is null. + public virtual Response UploadFile(Stream data, FilePurpose purpose, string filename = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(data, nameof(data)); + + UploadFileRequest uploadFileRequest = new UploadFileRequest(data, purpose, filename, null); + using MultipartFormDataRequestContent content = uploadFileRequest.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = UploadFile(content, content.ContentType, context); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// + /// [Protocol Method] Uploads a file for use by other operations. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task UploadFileAsync(RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.UploadFile"); + scope.Start(); + try + { + using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Uploads a file for use by other operations. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response UploadFile(RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.UploadFile"); + scope.Start(); + try + { + using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Delete a previously uploaded file. + /// The ID of the file to delete. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> DeleteFileAsync(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await DeleteFileAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(FileDeletionStatus.FromResponse(response), response); + } + + /// Delete a previously uploaded file. + /// The ID of the file to delete. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response DeleteFile(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = DeleteFile(fileId, context); + return Response.FromValue(FileDeletionStatus.FromResponse(response), response); + } + + /// + /// [Protocol Method] Delete a previously uploaded file. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task DeleteFileAsync(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.DeleteFile"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteFileRequest(fileId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Delete a previously uploaded file. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response DeleteFile(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.DeleteFile"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteFileRequest(fileId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetFileAsync(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetFileAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetFile(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetFile(fileId, context); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetFileAsync(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFile"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFileRequest(fileId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetFile(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFile"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFileRequest(fileId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetFileContentAsync(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetFileContentAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(response.Content, response); + } + + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetFileContent(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetFileContent(fileId, context); + return Response.FromValue(response.Content, response); + } + + /// + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetFileContentAsync(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFileContent"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFileContentRequest(fileId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetFileContent(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFileContent"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFileContentRequest(fileId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets a list of all batches owned by the Azure OpenAI resource. + /// Identifier for the last event from the previous pagination request. + /// Number of batches to retrieve. Defaults to 20. + /// The cancellation token to use. + public virtual async Task> GetBatchesAsync(string after = null, int? limit = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetBatchesAsync(after, limit, context).ConfigureAwait(false); + return Response.FromValue(OpenAIPageableListOfBatch.FromResponse(response), response); + } + + /// Gets a list of all batches owned by the Azure OpenAI resource. + /// Identifier for the last event from the previous pagination request. + /// Number of batches to retrieve. Defaults to 20. + /// The cancellation token to use. + public virtual Response GetBatches(string after = null, int? limit = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetBatches(after, limit, context); + return Response.FromValue(OpenAIPageableListOfBatch.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets a list of all batches owned by the Azure OpenAI resource. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Identifier for the last event from the previous pagination request. + /// Number of batches to retrieve. Defaults to 20. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetBatchesAsync(string after, int? limit, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetBatches"); + scope.Start(); + try + { + using HttpMessage message = CreateGetBatchesRequest(after, limit, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a list of all batches owned by the Azure OpenAI resource. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Identifier for the last event from the previous pagination request. + /// Number of batches to retrieve. Defaults to 20. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetBatches(string after, int? limit, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetBatches"); + scope.Start(); + try + { + using HttpMessage message = CreateGetBatchesRequest(after, limit, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Creates and executes a batch from an uploaded file of requests. + /// Response includes details of the enqueued job including job status. + /// The ID of the result file is added to the response once complete. + /// + /// The specification of the batch to create and execute. + /// The cancellation token to use. + /// is null. + public virtual async Task> CreateBatchAsync(BatchCreateRequest createBatchRequest, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(createBatchRequest, nameof(createBatchRequest)); + + using RequestContent content = createBatchRequest.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateBatchAsync(content, context).ConfigureAwait(false); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// + /// Creates and executes a batch from an uploaded file of requests. + /// Response includes details of the enqueued job including job status. + /// The ID of the result file is added to the response once complete. + /// + /// The specification of the batch to create and execute. + /// The cancellation token to use. + /// is null. + public virtual Response CreateBatch(BatchCreateRequest createBatchRequest, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(createBatchRequest, nameof(createBatchRequest)); + + using RequestContent content = createBatchRequest.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateBatch(content, context); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates and executes a batch from an uploaded file of requests. + /// Response includes details of the enqueued job including job status. + /// The ID of the result file is added to the response once complete. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CreateBatchAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CreateBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateBatchRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates and executes a batch from an uploaded file of requests. + /// Response includes details of the enqueued job including job status. + /// The ID of the result file is added to the response once complete. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CreateBatch(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CreateBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateBatchRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets details for a single batch specified by the given batchID. + /// The identifier of the batch. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetBatchAsync(string batchId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetBatchAsync(batchId, context).ConfigureAwait(false); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// Gets details for a single batch specified by the given batchID. + /// The identifier of the batch. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetBatch(string batchId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetBatch(batchId, context); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets details for a single batch specified by the given batchID. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The identifier of the batch. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetBatchAsync(string batchId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateGetBatchRequest(batchId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets details for a single batch specified by the given batchID. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The identifier of the batch. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetBatch(string batchId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateGetBatchRequest(batchId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets details for a single batch specified by the given batchID. + /// The identifier of the batch. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CancelBatchAsync(string batchId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CancelBatchAsync(batchId, context).ConfigureAwait(false); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// Gets details for a single batch specified by the given batchID. + /// The identifier of the batch. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CancelBatch(string batchId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CancelBatch(batchId, context); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets details for a single batch specified by the given batchID. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The identifier of the batch. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CancelBatchAsync(string batchId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CancelBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelBatchRequest(batchId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets details for a single batch specified by the given batchID. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The identifier of the batch. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CancelBatch(string batchId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CancelBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelBatchRequest(batchId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Creates an intermediate Upload object that you can add Parts to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + /// + /// Once you complete the Upload, we will create a File object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + /// + /// For certain purposes, the correct mime_type must be specified. Please refer to documentation for the supported MIME types for your use case. + /// + /// For guidance on the proper filename extensions for each purpose, please follow the documentation on creating a File. + /// + /// The request body for the operation options. + /// The cancellation token to use. + /// is null. + public virtual async Task> CreateUploadAsync(CreateUploadRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using RequestContent content = requestBody.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateUploadAsync(content, context).ConfigureAwait(false); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// + /// Creates an intermediate Upload object that you can add Parts to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + /// + /// Once you complete the Upload, we will create a File object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + /// + /// For certain purposes, the correct mime_type must be specified. Please refer to documentation for the supported MIME types for your use case. + /// + /// For guidance on the proper filename extensions for each purpose, please follow the documentation on creating a File. + /// + /// The request body for the operation options. + /// The cancellation token to use. + /// is null. + public virtual Response CreateUpload(CreateUploadRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using RequestContent content = requestBody.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateUpload(content, context); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates an intermediate Upload object that you can add Parts to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + /// + /// Once you complete the Upload, we will create a File object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + /// + /// For certain purposes, the correct mime_type must be specified. Please refer to documentation for the supported MIME types for your use case. + /// + /// For guidance on the proper filename extensions for each purpose, please follow the documentation on creating a File. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CreateUploadAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CreateUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateUploadRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates an intermediate Upload object that you can add Parts to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + /// + /// Once you complete the Upload, we will create a File object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + /// + /// For certain purposes, the correct mime_type must be specified. Please refer to documentation for the supported MIME types for your use case. + /// + /// For guidance on the proper filename extensions for each purpose, please follow the documentation on creating a File. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CreateUpload(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CreateUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateUploadRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Adds a Part to an Upload object. A Part represents a chunk of bytes from the file you are trying to upload. + /// + /// Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + /// + /// It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you complete the Upload. + /// + /// The ID of the upload associated with this operation. + /// The request body data payload for the operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> AddUploadPartAsync(string uploadId, AddUploadPartRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using MultipartFormDataRequestContent content = requestBody.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await AddUploadPartAsync(uploadId, content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(UploadPart.FromResponse(response), response); + } + + /// + /// Adds a Part to an Upload object. A Part represents a chunk of bytes from the file you are trying to upload. + /// + /// Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + /// + /// It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you complete the Upload. + /// + /// The ID of the upload associated with this operation. + /// The request body data payload for the operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response AddUploadPart(string uploadId, AddUploadPartRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using MultipartFormDataRequestContent content = requestBody.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = AddUploadPart(uploadId, content, content.ContentType, context); + return Response.FromValue(UploadPart.FromResponse(response), response); + } + + /// + /// [Protocol Method] Adds a Part to an Upload object. A Part represents a chunk of bytes from the file you are trying to upload. + /// + /// Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + /// + /// It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you complete the Upload. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The content to send as the body of the request. + /// The multipart/form-data content-type header for the operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task AddUploadPartAsync(string uploadId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.AddUploadPart"); + scope.Start(); + try + { + using HttpMessage message = CreateAddUploadPartRequest(uploadId, content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Adds a Part to an Upload object. A Part represents a chunk of bytes from the file you are trying to upload. + /// + /// Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + /// + /// It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you complete the Upload. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The content to send as the body of the request. + /// The multipart/form-data content-type header for the operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response AddUploadPart(string uploadId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.AddUploadPart"); + scope.Start(); + try + { + using HttpMessage message = CreateAddUploadPartRequest(uploadId, content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Completes the Upload. + /// + /// Within the returned Upload object, there is a nested File object that is ready to use in the rest of the platform. + /// + /// You can specify the order of the Parts by passing in an ordered list of the Part IDs. + /// + /// The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + /// + /// The ID of the upload associated with this operation. + /// The request body for the completion operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CompleteUploadAsync(string uploadId, CompleteUploadRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using RequestContent content = requestBody.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CompleteUploadAsync(uploadId, content, context).ConfigureAwait(false); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// + /// Completes the Upload. + /// + /// Within the returned Upload object, there is a nested File object that is ready to use in the rest of the platform. + /// + /// You can specify the order of the Parts by passing in an ordered list of the Part IDs. + /// + /// The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + /// + /// The ID of the upload associated with this operation. + /// The request body for the completion operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CompleteUpload(string uploadId, CompleteUploadRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using RequestContent content = requestBody.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CompleteUpload(uploadId, content, context); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// + /// [Protocol Method] Completes the Upload. + /// + /// Within the returned Upload object, there is a nested File object that is ready to use in the rest of the platform. + /// + /// You can specify the order of the Parts by passing in an ordered list of the Part IDs. + /// + /// The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CompleteUploadAsync(string uploadId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CompleteUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCompleteUploadRequest(uploadId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Completes the Upload. + /// + /// Within the returned Upload object, there is a nested File object that is ready to use in the rest of the platform. + /// + /// You can specify the order of the Parts by passing in an ordered list of the Part IDs. + /// + /// The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CompleteUpload(string uploadId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CompleteUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCompleteUploadRequest(uploadId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Cancels the Upload. No Parts may be added after an Upload is cancelled. + /// The ID of the upload associated with this operation. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CancelUploadAsync(string uploadId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CancelUploadAsync(uploadId, context).ConfigureAwait(false); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// Cancels the Upload. No Parts may be added after an Upload is cancelled. + /// The ID of the upload associated with this operation. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CancelUpload(string uploadId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CancelUpload(uploadId, context); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// + /// [Protocol Method] Cancels the Upload. No Parts may be added after an Upload is cancelled. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CancelUploadAsync(string uploadId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CancelUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelUploadRequest(uploadId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Cancels the Upload. No Parts may be added after an Upload is cancelled. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CancelUpload(string uploadId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CancelUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelUploadRequest(uploadId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateGetAudioTranscriptionAsPlainTextRequest(string deploymentId, RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/audio/transcriptions", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "text/plain"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetAudioTranscriptionAsResponseObjectRequest(string deploymentId, RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/audio/transcriptions", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetAudioTranslationAsPlainTextRequest(string deploymentId, RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/audio/translations", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "text/plain"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetAudioTranslationAsResponseObjectRequest(string deploymentId, RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/audio/translations", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetCompletionsRequest(string deploymentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/completions", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetChatCompletionsRequest(string deploymentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/chat/completions", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetImageGenerationsRequest(string deploymentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/images/generations", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGenerateSpeechFromTextRequest(string deploymentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/audio/speech", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/octet-stream"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetEmbeddingsRequest(string deploymentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/embeddings", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetFilesRequest(string purpose, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/files", false); + if (purpose != null) + { + uri.AppendQuery("purpose", purpose, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateUploadFileRequest(RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/files", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateDeleteFileRequest(string fileId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetFileRequest(string fileId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetFileContentRequest(string fileId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + uri.AppendPath("/content", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetBatchesRequest(string after, int? limit, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/batches", false); + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateBatchRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier201); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/batches", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetBatchRequest(string batchId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/batches/", false); + uri.AppendPath(batchId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCancelBatchRequest(string batchId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/batches/", false); + uri.AppendPath(batchId, true); + uri.AppendPath("/cancel", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateUploadRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/uploads", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateAddUploadPartRequest(string uploadId, RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/parts", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateCompleteUploadRequest(string uploadId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/complete", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateCancelUploadRequest(string uploadId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/cancel", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier201; + private static ResponseClassifier ResponseClassifier201 => _responseClassifier201 ??= new StatusCodeClassifier(stackalloc ushort[] { 201 }); + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClientOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClientOptions.cs new file mode 100644 index 000000000000..1aa87f12833e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClientOptions.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + /// Client options for OpenAIClient. + public partial class OpenAIClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2024_09_01_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2022-12-01". + V2022_12_01 = 1, + /// Service version "2023-05-15". + V2023_05_15 = 2, + /// Service version "2023-06-01-preview". + V2023_06_01_Preview = 3, + /// Service version "2023-07-01-preview". + V2023_07_01_Preview = 4, + /// Service version "2024-02-01". + V2024_02_01 = 5, + /// Service version "2024-02-15-preview". + V2024_02_15_Preview = 6, + /// Service version "2024-03-01-preview". + V2024_03_01_Preview = 7, + /// Service version "2024-04-01-preview". + V2024_04_01_Preview = 8, + /// Service version "2024-05-01-preview". + V2024_05_01_Preview = 9, + /// Service version "2024-06-01". + V2024_06_01 = 10, + /// Service version "2024-07-01-preview". + V2024_07_01_Preview = 11, + /// Service version "2024-08-01-preview". + V2024_08_01_Preview = 12, + /// Service version "2024-09-01-preview". + V2024_09_01_Preview = 13, + } + + internal string Version { get; } + + /// Initializes new instance of OpenAIClientOptions. + public OpenAIClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2022_12_01 => "2022-12-01", + ServiceVersion.V2023_05_15 => "2023-05-15", + ServiceVersion.V2023_06_01_Preview => "2023-06-01-preview", + ServiceVersion.V2023_07_01_Preview => "2023-07-01-preview", + ServiceVersion.V2024_02_01 => "2024-02-01", + ServiceVersion.V2024_02_15_Preview => "2024-02-15-preview", + ServiceVersion.V2024_03_01_Preview => "2024-03-01-preview", + ServiceVersion.V2024_04_01_Preview => "2024-04-01-preview", + ServiceVersion.V2024_05_01_Preview => "2024-05-01-preview", + ServiceVersion.V2024_06_01 => "2024-06-01", + ServiceVersion.V2024_07_01_Preview => "2024-07-01-preview", + ServiceVersion.V2024_08_01_Preview => "2024-08-01-preview", + ServiceVersion.V2024_09_01_Preview => "2024-09-01-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.Serialization.cs new file mode 100644 index 000000000000..a15be530ce6d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.Serialization.cs @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OpenAIFile : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OpenAIFile)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("bytes"u8); + writer.WriteNumberValue(Bytes); + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose.ToString()); + if (Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.Value.ToString()); + } + if (Optional.IsDefined(StatusDetails)) + { + writer.WritePropertyName("status_details"u8); + writer.WriteStringValue(StatusDetails); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OpenAIFile 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(OpenAIFile)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOpenAIFile(document.RootElement, options); + } + + internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OpenAIFileObject @object = default; + string id = default; + int bytes = default; + string filename = default; + DateTimeOffset createdAt = default; + FilePurpose purpose = default; + FileState? status = default; + string statusDetails = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("object"u8)) + { + @object = new OpenAIFileObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("bytes"u8)) + { + bytes = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("purpose"u8)) + { + purpose = new FilePurpose(property.Value.GetString()); + continue; + } + if (property.NameEquals("status"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new FileState(property.Value.GetString()); + continue; + } + if (property.NameEquals("status_details"u8)) + { + statusDetails = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OpenAIFile( + @object, + id, + bytes, + filename, + createdAt, + purpose, + status, + statusDetails, + serializedAdditionalRawData); + } + + 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(OpenAIFile)} does not support writing '{options.Format}' format."); + } + } + + OpenAIFile 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 DeserializeOpenAIFile(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OpenAIFile)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OpenAIFile FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOpenAIFile(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.cs similarity index 51% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.cs index 119a216efc63..a9eddeb3b1c6 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.cs @@ -8,10 +8,10 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI.Assistants +namespace Azure.AI.OpenAI { - /// Information about a file attached to an assistant, as used by tools that can read files. - public partial class AssistantFile + /// Represents an assistant that can call the model and use tools. + public partial class OpenAIFile { /// /// Keeps track of any properties unknown to the library. @@ -45,47 +45,69 @@ public partial class AssistantFile /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The identifier, which can be referenced in API endpoints. + /// The size of the file, in bytes. + /// The name of the file. /// The Unix timestamp, in seconds, representing when this object was created. - /// The assistant ID that the file is attached to. - /// or is null. - internal AssistantFile(string id, DateTimeOffset createdAt, string assistantId) + /// The intended purpose of a file. + /// or is null. + internal OpenAIFile(string id, int bytes, string filename, DateTimeOffset createdAt, FilePurpose purpose) { Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(assistantId, nameof(assistantId)); + Argument.AssertNotNull(filename, nameof(filename)); Id = id; + Bytes = bytes; + Filename = filename; CreatedAt = createdAt; - AssistantId = assistantId; + Purpose = purpose; } - /// Initializes a new instance of . + /// Initializes a new instance of . + /// The object type, which is always 'file'. /// The identifier, which can be referenced in API endpoints. - /// The object type, which is always 'assistant.file'. + /// The size of the file, in bytes. + /// The name of the file. /// The Unix timestamp, in seconds, representing when this object was created. - /// The assistant ID that the file is attached to. + /// The intended purpose of a file. + /// The state of the file. This field is available in Azure OpenAI only. + /// The error message with details in case processing of this file failed. This field is available in Azure OpenAI only. /// Keeps track of any properties unknown to the library. - internal AssistantFile(string id, string @object, DateTimeOffset createdAt, string assistantId, IDictionary serializedAdditionalRawData) + internal OpenAIFile(OpenAIFileObject @object, string id, int bytes, string filename, DateTimeOffset createdAt, FilePurpose purpose, FileState? status, string statusDetails, IDictionary serializedAdditionalRawData) { - Id = id; Object = @object; + Id = id; + Bytes = bytes; + Filename = filename; CreatedAt = createdAt; - AssistantId = assistantId; + Purpose = purpose; + Status = status; + StatusDetails = statusDetails; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal AssistantFile() + /// Initializes a new instance of for deserialization. + internal OpenAIFile() { } + /// The object type, which is always 'file'. + public OpenAIFileObject Object { get; } = OpenAIFileObject.File; + /// The identifier, which can be referenced in API endpoints. public string Id { get; } - + /// The size of the file, in bytes. + public int Bytes { get; } + /// The name of the file. + public string Filename { get; } /// The Unix timestamp, in seconds, representing when this object was created. public DateTimeOffset CreatedAt { get; } - /// The assistant ID that the file is attached to. - public string AssistantId { get; } + /// The intended purpose of a file. + public FilePurpose Purpose { get; } + /// The state of the file. This field is available in Azure OpenAI only. + public FileState? Status { get; } + /// The error message with details in case processing of this file failed. This field is available in Azure OpenAI only. + public string StatusDetails { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFileObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFileObject.cs new file mode 100644 index 000000000000..8268140265ee --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFileObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The OpenAIFile_object. + public readonly partial struct OpenAIFileObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OpenAIFileObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FileValue = "file"; + + /// file. + public static OpenAIFileObject File { get; } = new OpenAIFileObject(FileValue); + /// Determines if two values are the same. + public static bool operator ==(OpenAIFileObject left, OpenAIFileObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OpenAIFileObject left, OpenAIFileObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OpenAIFileObject(string value) => new OpenAIFileObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OpenAIFileObject other && Equals(other); + /// + public bool Equals(OpenAIFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.Serialization.cs new file mode 100644 index 000000000000..f783cbe928a4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.Serialization.cs @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OpenAIPageableListOfBatch : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OpenAIPageableListOfBatch)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (Optional.IsCollectionDefined(Data)) + { + writer.WritePropertyName("data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(FirstId)) + { + writer.WritePropertyName("first_id"u8); + writer.WriteStringValue(FirstId); + } + if (Optional.IsDefined(LastId)) + { + writer.WritePropertyName("last_id"u8); + writer.WriteStringValue(LastId); + } + if (Optional.IsDefined(HasMore)) + { + writer.WritePropertyName("has_more"u8); + writer.WriteBooleanValue(HasMore.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OpenAIPageableListOfBatch 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(OpenAIPageableListOfBatch)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOpenAIPageableListOfBatch(document.RootElement, options); + } + + internal static OpenAIPageableListOfBatch DeserializeOpenAIPageableListOfBatch(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OpenAIPageableListOfBatchObject @object = default; + IReadOnlyList data = default; + string firstId = default; + string lastId = default; + bool? hasMore = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("object"u8)) + { + @object = new OpenAIPageableListOfBatchObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("data"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(OpenAI.Batch.DeserializeBatch(item, options)); + } + data = array; + continue; + } + if (property.NameEquals("first_id"u8)) + { + firstId = property.Value.GetString(); + continue; + } + if (property.NameEquals("last_id"u8)) + { + lastId = property.Value.GetString(); + continue; + } + if (property.NameEquals("has_more"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + hasMore = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OpenAIPageableListOfBatch( + @object, + data ?? new ChangeTrackingList(), + firstId, + lastId, + hasMore, + serializedAdditionalRawData); + } + + 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(OpenAIPageableListOfBatch)} does not support writing '{options.Format}' format."); + } + } + + OpenAIPageableListOfBatch 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 DeserializeOpenAIPageableListOfBatch(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OpenAIPageableListOfBatch)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OpenAIPageableListOfBatch FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeOpenAIPageableListOfBatch(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.cs new file mode 100644 index 000000000000..16be6cb0109c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The response data for a requested list of items. + public partial class OpenAIPageableListOfBatch + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal OpenAIPageableListOfBatch() + { + Data = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The object type, which is always list. + /// The requested list of items. + /// The first ID represented in this list. + /// The last ID represented in this list. + /// A value indicating whether there are additional values available not captured in this list. + /// Keeps track of any properties unknown to the library. + internal OpenAIPageableListOfBatch(OpenAIPageableListOfBatchObject @object, IReadOnlyList data, string firstId, string lastId, bool? hasMore, IDictionary serializedAdditionalRawData) + { + Object = @object; + Data = data; + FirstId = firstId; + LastId = lastId; + HasMore = hasMore; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type, which is always list. + public OpenAIPageableListOfBatchObject Object { get; } = OpenAIPageableListOfBatchObject.List; + + /// The requested list of items. + public IReadOnlyList Data { get; } + /// The first ID represented in this list. + public string FirstId { get; } + /// The last ID represented in this list. + public string LastId { get; } + /// A value indicating whether there are additional values available not captured in this list. + public bool? HasMore { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatchObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatchObject.cs new file mode 100644 index 000000000000..db12e107d15c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatchObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The OpenAIPageableListOfBatch_object. + public readonly partial struct OpenAIPageableListOfBatchObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OpenAIPageableListOfBatchObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ListValue = "list"; + + /// list. + public static OpenAIPageableListOfBatchObject List { get; } = new OpenAIPageableListOfBatchObject(ListValue); + /// Determines if two values are the same. + public static bool operator ==(OpenAIPageableListOfBatchObject left, OpenAIPageableListOfBatchObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OpenAIPageableListOfBatchObject left, OpenAIPageableListOfBatchObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OpenAIPageableListOfBatchObject(string value) => new OpenAIPageableListOfBatchObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OpenAIPageableListOfBatchObject other && Equals(other); + /// + public bool Equals(OpenAIPageableListOfBatchObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatDataSource.Serialization.cs deleted file mode 100644 index ca7bb2911d1c..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatDataSource.Serialization.cs +++ /dev/null @@ -1,147 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI.Chat -{ - public partial class PineconeChatDataSource : 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(PineconeChatDataSource)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("parameters") != true) - { - writer.WritePropertyName("parameters"u8); - writer.WriteObjectValue(InternalParameters, options); - } - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - writer.WriteEndObject(); - } - - PineconeChatDataSource 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(PineconeChatDataSource)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePineconeChatDataSource(document.RootElement, options); - } - - internal static PineconeChatDataSource DeserializePineconeChatDataSource(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - InternalPineconeChatDataSourceParameters parameters = default; - string type = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("parameters"u8)) - { - parameters = InternalPineconeChatDataSourceParameters.DeserializeInternalPineconeChatDataSourceParameters(property.Value, options); - continue; - } - if (property.NameEquals("type"u8)) - { - type = property.Value.GetString(); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new PineconeChatDataSource(type, serializedAdditionalRawData, parameters); - } - - 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(PineconeChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - PineconeChatDataSource 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 DeserializePineconeChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PineconeChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new PineconeChatDataSource FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializePineconeChatDataSource(document.RootElement); - } - - /// Convert into a . - internal override BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatDataSource.cs deleted file mode 100644 index 213c4559cc44..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatDataSource.cs +++ /dev/null @@ -1,14 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The PineconeChatDataSource. - public partial class PineconeChatDataSource : ChatDataSource - { - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..506936da82dc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class PineconeChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(PineconeChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("parameters"u8); + writer.WriteObjectValue(Parameters, options); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + PineconeChatExtensionConfiguration 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(PineconeChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePineconeChatExtensionConfiguration(document.RootElement, options); + } + + internal static PineconeChatExtensionConfiguration DeserializePineconeChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + PineconeChatExtensionParameters parameters = default; + AzureChatExtensionType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("parameters"u8)) + { + parameters = PineconeChatExtensionParameters.DeserializePineconeChatExtensionParameters(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PineconeChatExtensionConfiguration(type, serializedAdditionalRawData, parameters); + } + + 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(PineconeChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + PineconeChatExtensionConfiguration 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 DeserializePineconeChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PineconeChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new PineconeChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializePineconeChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.cs new file mode 100644 index 000000000000..047937523042 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A specific representation of configurable options for Pinecone when using it as an Azure OpenAI chat + /// extension. + /// + public partial class PineconeChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// The parameters to use when configuring Azure OpenAI chat extensions. + /// is null. + public PineconeChatExtensionConfiguration(PineconeChatExtensionParameters parameters) + { + Argument.AssertNotNull(parameters, nameof(parameters)); + + Type = AzureChatExtensionType.Pinecone; + Parameters = parameters; + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + /// The parameters to use when configuring Azure OpenAI chat extensions. + internal PineconeChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData, PineconeChatExtensionParameters parameters) : base(type, serializedAdditionalRawData) + { + Parameters = parameters; + } + + /// Initializes a new instance of for deserialization. + internal PineconeChatExtensionConfiguration() + { + } + + /// The parameters to use when configuring Azure OpenAI chat extensions. + public PineconeChatExtensionParameters Parameters { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalPineconeChatDataSourceParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.Serialization.cs similarity index 54% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/InternalPineconeChatDataSourceParameters.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.Serialization.cs index 9e985538ecb7..5ad877e32bf8 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalPineconeChatDataSourceParameters.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.Serialization.cs @@ -1,94 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - internal partial class InternalPineconeChatDataSourceParameters : IJsonModel + public partial class PineconeChatExtensionParameters : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(InternalPineconeChatDataSourceParameters)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(PineconeChatExtensionParameters)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("top_n_documents") != true && Optional.IsDefined(TopNDocuments)) + if (Optional.IsDefined(DocumentCount)) { writer.WritePropertyName("top_n_documents"u8); - writer.WriteNumberValue(TopNDocuments.Value); + writer.WriteNumberValue(DocumentCount.Value); } - if (SerializedAdditionalRawData?.ContainsKey("in_scope") != true && Optional.IsDefined(InScope)) + if (Optional.IsDefined(ShouldRestrictResultScope)) { writer.WritePropertyName("in_scope"u8); - writer.WriteBooleanValue(InScope.Value); + writer.WriteBooleanValue(ShouldRestrictResultScope.Value); } - if (SerializedAdditionalRawData?.ContainsKey("strictness") != true && Optional.IsDefined(Strictness)) + if (Optional.IsDefined(Strictness)) { writer.WritePropertyName("strictness"u8); writer.WriteNumberValue(Strictness.Value); } - if (SerializedAdditionalRawData?.ContainsKey("max_search_queries") != true && Optional.IsDefined(MaxSearchQueries)) + if (Optional.IsDefined(MaxSearchQueries)) { writer.WritePropertyName("max_search_queries"u8); writer.WriteNumberValue(MaxSearchQueries.Value); } - if (SerializedAdditionalRawData?.ContainsKey("allow_partial_result") != true && Optional.IsDefined(AllowPartialResult)) + if (Optional.IsDefined(AllowPartialResult)) { writer.WritePropertyName("allow_partial_result"u8); writer.WriteBooleanValue(AllowPartialResult.Value); } - if (SerializedAdditionalRawData?.ContainsKey("include_contexts") != true && Optional.IsCollectionDefined(_internalIncludeContexts)) + if (Optional.IsCollectionDefined(IncludeContexts)) { writer.WritePropertyName("include_contexts"u8); writer.WriteStartArray(); - foreach (var item in _internalIncludeContexts) + foreach (var item in IncludeContexts) { - writer.WriteStringValue(item); + writer.WriteStringValue(item.ToString()); } writer.WriteEndArray(); } - if (SerializedAdditionalRawData?.ContainsKey("environment") != true) - { - writer.WritePropertyName("environment"u8); - writer.WriteStringValue(Environment); - } - if (SerializedAdditionalRawData?.ContainsKey("index_name") != true) - { - writer.WritePropertyName("index_name"u8); - writer.WriteStringValue(IndexName); - } - if (SerializedAdditionalRawData?.ContainsKey("authentication") != true) + if (Optional.IsDefined(Authentication)) { writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); - } - if (SerializedAdditionalRawData?.ContainsKey("embedding_dependency") != true) - { - writer.WritePropertyName("embedding_dependency"u8); - writer.WriteObjectValue(VectorizationSource, options); + writer.WriteObjectValue(Authentication, options); } - if (SerializedAdditionalRawData?.ContainsKey("fields_mapping") != true) + writer.WritePropertyName("environment"u8); + writer.WriteStringValue(EnvironmentName); + writer.WritePropertyName("index_name"u8); + writer.WriteStringValue(IndexName); + writer.WritePropertyName("fields_mapping"u8); + writer.WriteObjectValue(FieldMappingOptions, options); + writer.WritePropertyName("embedding_dependency"u8); + writer.WriteObjectValue(EmbeddingDependency, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) { - writer.WritePropertyName("fields_mapping"u8); - writer.WriteObjectValue(FieldMappings, options); - } - if (SerializedAdditionalRawData != null) - { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -103,19 +92,19 @@ void IJsonModel.Write(Utf8JsonWriter w writer.WriteEndObject(); } - InternalPineconeChatDataSourceParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + PineconeChatExtensionParameters 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(InternalPineconeChatDataSourceParameters)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(PineconeChatExtensionParameters)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalPineconeChatDataSourceParameters(document.RootElement, options); + return DeserializePineconeChatExtensionParameters(document.RootElement, options); } - internal static InternalPineconeChatDataSourceParameters DeserializeInternalPineconeChatDataSourceParameters(JsonElement element, ModelReaderWriterOptions options = null) + internal static PineconeChatExtensionParameters DeserializePineconeChatExtensionParameters(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -128,12 +117,12 @@ internal static InternalPineconeChatDataSourceParameters DeserializeInternalPine int? strictness = default; int? maxSearchQueries = default; bool? allowPartialResult = default; - IList includeContexts = default; + IList includeContexts = default; + OnYourDataAuthenticationOptions authentication = default; string environment = default; string indexName = default; - DataSourceAuthentication authentication = default; - DataSourceVectorizer embeddingDependency = default; - DataSourceFieldMappings fieldsMapping = default; + PineconeFieldMappingOptions fieldsMapping = default; + OnYourDataVectorizationSource embeddingDependency = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -189,14 +178,23 @@ internal static InternalPineconeChatDataSourceParameters DeserializeInternalPine { continue; } - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(item.GetString()); + array.Add(new OnYourDataContextProperty(item.GetString())); } includeContexts = array; continue; } + if (property.NameEquals("authentication"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + authentication = OnYourDataAuthenticationOptions.DeserializeOnYourDataAuthenticationOptions(property.Value, options); + continue; + } if (property.NameEquals("environment"u8)) { environment = property.Value.GetString(); @@ -207,87 +205,82 @@ internal static InternalPineconeChatDataSourceParameters DeserializeInternalPine indexName = property.Value.GetString(); continue; } - if (property.NameEquals("authentication"u8)) + if (property.NameEquals("fields_mapping"u8)) { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(property.Value, options); + fieldsMapping = PineconeFieldMappingOptions.DeserializePineconeFieldMappingOptions(property.Value, options); continue; } if (property.NameEquals("embedding_dependency"u8)) { - embeddingDependency = DataSourceVectorizer.DeserializeDataSourceVectorizer(property.Value, options); - continue; - } - if (property.NameEquals("fields_mapping"u8)) - { - fieldsMapping = DataSourceFieldMappings.DeserializeDataSourceFieldMappings(property.Value, options); + embeddingDependency = OnYourDataVectorizationSource.DeserializeOnYourDataVectorizationSource(property.Value, options); continue; } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new InternalPineconeChatDataSourceParameters( + return new PineconeChatExtensionParameters( topNDocuments, inScope, strictness, maxSearchQueries, allowPartialResult, - includeContexts ?? new ChangeTrackingList(), + includeContexts ?? new ChangeTrackingList(), + authentication, environment, indexName, - authentication, - embeddingDependency, fieldsMapping, + embeddingDependency, 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(InternalPineconeChatDataSourceParameters)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(PineconeChatExtensionParameters)} does not support writing '{options.Format}' format."); } } - InternalPineconeChatDataSourceParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + PineconeChatExtensionParameters 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 DeserializeInternalPineconeChatDataSourceParameters(document.RootElement, options); + return DeserializePineconeChatExtensionParameters(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalPineconeChatDataSourceParameters)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(PineconeChatExtensionParameters)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static InternalPineconeChatDataSourceParameters FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static PineconeChatExtensionParameters FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalPineconeChatDataSourceParameters(document.RootElement); + return DeserializePineconeChatExtensionParameters(document.RootElement); } - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() + /// Convert into a . + internal virtual RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.cs new file mode 100644 index 000000000000..7f1a38f68a42 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.cs @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Parameters for configuring Azure OpenAI Pinecone chat extensions. The supported authentication type is APIKey. + public partial class PineconeChatExtensionParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The environment name of Pinecone. + /// The name of the Pinecone database index. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// , , or is null. + public PineconeChatExtensionParameters(string environmentName, string indexName, PineconeFieldMappingOptions fieldMappingOptions, OnYourDataVectorizationSource embeddingDependency) + { + Argument.AssertNotNull(environmentName, nameof(environmentName)); + Argument.AssertNotNull(indexName, nameof(indexName)); + Argument.AssertNotNull(fieldMappingOptions, nameof(fieldMappingOptions)); + Argument.AssertNotNull(embeddingDependency, nameof(embeddingDependency)); + + IncludeContexts = new ChangeTrackingList(); + EnvironmentName = environmentName; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + EmbeddingDependency = embeddingDependency; + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The environment name of Pinecone. + /// The name of the Pinecone database index. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// Keeps track of any properties unknown to the library. + internal PineconeChatExtensionParameters(int? documentCount, bool? shouldRestrictResultScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList includeContexts, OnYourDataAuthenticationOptions authentication, string environmentName, string indexName, PineconeFieldMappingOptions fieldMappingOptions, OnYourDataVectorizationSource embeddingDependency, IDictionary serializedAdditionalRawData) + { + DocumentCount = documentCount; + ShouldRestrictResultScope = shouldRestrictResultScope; + Strictness = strictness; + MaxSearchQueries = maxSearchQueries; + AllowPartialResult = allowPartialResult; + IncludeContexts = includeContexts; + Authentication = authentication; + EnvironmentName = environmentName; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + EmbeddingDependency = embeddingDependency; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal PineconeChatExtensionParameters() + { + } + + /// The configured top number of documents to feature for the configured query. + public int? DocumentCount { get; set; } + /// Whether queries should be restricted to use of indexed data. + public bool? ShouldRestrictResultScope { get; set; } + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + public int? Strictness { get; set; } + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + public int? MaxSearchQueries { get; set; } + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + public bool? AllowPartialResult { get; set; } + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + public IList IncludeContexts { get; } + /// + /// The authentication method to use when accessing the defined data source. + /// Each data source type supports a specific set of available authentication methods; please see the documentation of + /// the data source for supported mechanisms. + /// If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + /// authentication. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + public OnYourDataAuthenticationOptions Authentication { get; set; } + /// The environment name of Pinecone. + public string EnvironmentName { get; } + /// The name of the Pinecone database index. + public string IndexName { get; } + /// Customized field mapping behavior to use when interacting with the search index. + public PineconeFieldMappingOptions FieldMappingOptions { get; } + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public OnYourDataVectorizationSource EmbeddingDependency { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.Serialization.cs new file mode 100644 index 000000000000..1706fe6ec228 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.Serialization.cs @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class PineconeFieldMappingOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(PineconeFieldMappingOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + if (Optional.IsDefined(TitleFieldName)) + { + writer.WritePropertyName("title_field"u8); + writer.WriteStringValue(TitleFieldName); + } + if (Optional.IsDefined(UrlFieldName)) + { + writer.WritePropertyName("url_field"u8); + writer.WriteStringValue(UrlFieldName); + } + if (Optional.IsDefined(FilepathFieldName)) + { + writer.WritePropertyName("filepath_field"u8); + writer.WriteStringValue(FilepathFieldName); + } + writer.WritePropertyName("content_fields"u8); + writer.WriteStartArray(); + foreach (var item in ContentFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(ContentFieldSeparator)) + { + writer.WritePropertyName("content_fields_separator"u8); + writer.WriteStringValue(ContentFieldSeparator); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + PineconeFieldMappingOptions 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(PineconeFieldMappingOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePineconeFieldMappingOptions(document.RootElement, options); + } + + internal static PineconeFieldMappingOptions DeserializePineconeFieldMappingOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string titleField = default; + string urlField = default; + string filepathField = default; + IList contentFields = default; + string contentFieldsSeparator = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("title_field"u8)) + { + titleField = property.Value.GetString(); + continue; + } + if (property.NameEquals("url_field"u8)) + { + urlField = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath_field"u8)) + { + filepathField = property.Value.GetString(); + continue; + } + if (property.NameEquals("content_fields"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + contentFields = array; + continue; + } + if (property.NameEquals("content_fields_separator"u8)) + { + contentFieldsSeparator = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PineconeFieldMappingOptions( + titleField, + urlField, + filepathField, + contentFields, + contentFieldsSeparator, + serializedAdditionalRawData); + } + + 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(PineconeFieldMappingOptions)} does not support writing '{options.Format}' format."); + } + } + + PineconeFieldMappingOptions 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 DeserializePineconeFieldMappingOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PineconeFieldMappingOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static PineconeFieldMappingOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializePineconeFieldMappingOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.cs new file mode 100644 index 000000000000..4d3d569a6533 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Optional settings to control how fields are processed when using a configured Pinecone resource. + public partial class PineconeFieldMappingOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The names of index fields that should be treated as content. + /// is null. + public PineconeFieldMappingOptions(IEnumerable contentFieldNames) + { + Argument.AssertNotNull(contentFieldNames, nameof(contentFieldNames)); + + ContentFieldNames = contentFieldNames.ToList(); + } + + /// Initializes a new instance of . + /// The name of the index field to use as a title. + /// The name of the index field to use as a URL. + /// The name of the index field to use as a filepath. + /// The names of index fields that should be treated as content. + /// The separator pattern that content fields should use. + /// Keeps track of any properties unknown to the library. + internal PineconeFieldMappingOptions(string titleFieldName, string urlFieldName, string filepathFieldName, IList contentFieldNames, string contentFieldSeparator, IDictionary serializedAdditionalRawData) + { + TitleFieldName = titleFieldName; + UrlFieldName = urlFieldName; + FilepathFieldName = filepathFieldName; + ContentFieldNames = contentFieldNames; + ContentFieldSeparator = contentFieldSeparator; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal PineconeFieldMappingOptions() + { + } + + /// The name of the index field to use as a title. + public string TitleFieldName { get; set; } + /// The name of the index field to use as a URL. + public string UrlFieldName { get; set; } + /// The name of the index field to use as a filepath. + public string FilepathFieldName { get; set; } + /// The names of index fields that should be treated as content. + public IList ContentFieldNames { get; } + /// The separator pattern that content fields should use. + public string ContentFieldSeparator { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/RequestContentFilterResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/RequestContentFilterResult.Serialization.cs deleted file mode 100644 index 030bb75bd3c8..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/RequestContentFilterResult.Serialization.cs +++ /dev/null @@ -1,155 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - public partial class RequestContentFilterResult : 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(RequestContentFilterResult)} does not support writing '{format}' format."); - } - - writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("prompt_index") != true && Optional.IsDefined(PromptIndex)) - { - writer.WritePropertyName("prompt_index"u8); - writer.WriteNumberValue(PromptIndex.Value); - } - if (SerializedAdditionalRawData?.ContainsKey("content_filter_results") != true && Optional.IsDefined(InternalResults)) - { - writer.WritePropertyName("content_filter_results"u8); - writer.WriteObjectValue(InternalResults, 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(); - } - - RequestContentFilterResult 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(RequestContentFilterResult)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeRequestContentFilterResult(document.RootElement, options); - } - - internal static RequestContentFilterResult DeserializeRequestContentFilterResult(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? promptIndex = default; - InternalAzureContentFilterResultForPromptContentFilterResults contentFilterResults = default; - IDictionary serializedAdditionalRawData = default; - Dictionary rawDataDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("prompt_index"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - promptIndex = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("content_filter_results"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - contentFilterResults = InternalAzureContentFilterResultForPromptContentFilterResults.DeserializeInternalAzureContentFilterResultForPromptContentFilterResults(property.Value, options); - continue; - } - if (options.Format != "W") - { - rawDataDictionary ??= new Dictionary(); - rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - } - serializedAdditionalRawData = rawDataDictionary; - return new RequestContentFilterResult(promptIndex, contentFilterResults, serializedAdditionalRawData); - } - - 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(RequestContentFilterResult)} does not support writing '{options.Format}' format."); - } - } - - RequestContentFilterResult 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 DeserializeRequestContentFilterResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(RequestContentFilterResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static RequestContentFilterResult FromResponse(PipelineResponse response) - { - using var document = JsonDocument.Parse(response.Content); - return DeserializeRequestContentFilterResult(document.RootElement); - } - - /// Convert into a . - internal virtual BinaryContent ToBinaryContent() - { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/RequestImageContentFilterResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/RequestImageContentFilterResult.cs deleted file mode 100644 index e41fc322b0ee..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/RequestImageContentFilterResult.cs +++ /dev/null @@ -1,85 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// A content filter result for an image generation operation's input request content. - public partial class RequestImageContentFilterResult : ResponseImageContentFilterResult - { - /// Initializes a new instance of . - /// - /// A detection result that describes user prompt injection attacks, where malicious users deliberately exploit - /// system vulnerabilities to elicit unauthorized behavior from the LLM. This could lead to inappropriate content - /// generation or violations of system-imposed restrictions. - /// - /// is null. - internal RequestImageContentFilterResult(ContentFilterDetectionResult jailbreak) - { - Argument.AssertNotNull(jailbreak, nameof(jailbreak)); - - Jailbreak = jailbreak; - } - - /// Initializes a new instance of . - /// - /// A content filter category for language related to anatomical organs and genitals, romantic relationships, acts - /// portrayed in erotic or affectionate terms, pregnancy, physical sexual acts, including those portrayed as an - /// assault or a forced sexual violent act against one's will, prostitution, pornography, and abuse. - /// - /// - /// A content filter category for language related to physical actions intended to hurt, injure, damage, or kill - /// someone or something; describes weapons, guns and related entities, such as manufactures, associations, - /// legislation, and so on. - /// - /// - /// A content filter category that can refer to any content that attacks or uses pejorative or discriminatory - /// language with reference to a person or identity group based on certain differentiating attributes of these groups - /// including but not limited to race, ethnicity, nationality, gender identity and expression, sexual orientation, - /// religion, immigration status, ability status, personal appearance, and body size. - /// - /// - /// A content filter category that describes language related to physical actions intended to purposely hurt, injure, - /// damage one's body or kill oneself. - /// - /// Keeps track of any properties unknown to the library. - /// - /// A detection result that identifies whether crude, vulgar, or otherwise objection language is present in the - /// content. - /// - /// A collection of binary filtering outcomes for configured custom blocklists. - /// - /// A detection result that describes user prompt injection attacks, where malicious users deliberately exploit - /// system vulnerabilities to elicit unauthorized behavior from the LLM. This could lead to inappropriate content - /// generation or violations of system-imposed restrictions. - /// - internal RequestImageContentFilterResult(ContentFilterSeverityResult sexual, ContentFilterSeverityResult violence, ContentFilterSeverityResult hate, ContentFilterSeverityResult selfHarm, IDictionary serializedAdditionalRawData, ContentFilterDetectionResult profanity, ContentFilterBlocklistResult customBlocklists, ContentFilterDetectionResult jailbreak) : base(sexual, violence, hate, selfHarm, serializedAdditionalRawData) - { - Profanity = profanity; - CustomBlocklists = customBlocklists; - Jailbreak = jailbreak; - } - - /// Initializes a new instance of for deserialization. - internal RequestImageContentFilterResult() - { - } - - /// - /// A detection result that identifies whether crude, vulgar, or otherwise objection language is present in the - /// content. - /// - public ContentFilterDetectionResult Profanity { get; } - /// A collection of binary filtering outcomes for configured custom blocklists. - public ContentFilterBlocklistResult CustomBlocklists { get; } - /// - /// A detection result that describes user prompt injection attacks, where malicious users deliberately exploit - /// system vulnerabilities to elicit unauthorized behavior from the LLM. This could lead to inappropriate content - /// generation or violations of system-imposed restrictions. - /// - public ContentFilterDetectionResult Jailbreak { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseContentFilterResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseContentFilterResult.cs deleted file mode 100644 index be77b4567b3d..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseContentFilterResult.cs +++ /dev/null @@ -1,129 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// A content filter result for a single response item produced by a generative AI system. - public partial class ResponseContentFilterResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal ResponseContentFilterResult() - { - } - - /// Initializes a new instance of . - /// - /// A content filter category for language related to anatomical organs and genitals, romantic relationships, acts - /// portrayed in erotic or affectionate terms, pregnancy, physical sexual acts, including those portrayed as an - /// assault or a forced sexual violent act against one's will, prostitution, pornography, and abuse. - /// - /// - /// A content filter category that can refer to any content that attacks or uses pejorative or discriminatory - /// language with reference to a person or identity group based on certain differentiating attributes of these groups - /// including but not limited to race, ethnicity, nationality, gender identity and expression, sexual orientation, - /// religion, immigration status, ability status, personal appearance, and body size. - /// - /// - /// A content filter category for language related to physical actions intended to hurt, injure, damage, or kill - /// someone or something; describes weapons, guns and related entities, such as manufactures, associations, - /// legislation, and so on. - /// - /// - /// A content filter category that describes language related to physical actions intended to purposely hurt, injure, - /// damage one's body or kill oneself. - /// - /// - /// A detection result that identifies whether crude, vulgar, or otherwise objection language is present in the - /// content. - /// - /// A collection of binary filtering outcomes for configured custom blocklists. - /// If present, details about an error that prevented content filtering from completing its evaluation. - /// A detection result that describes a match against text protected under copyright or other status. - /// A detection result that describes a match against licensed code or other protected source material. - /// Keeps track of any properties unknown to the library. - internal ResponseContentFilterResult(ContentFilterSeverityResult sexual, ContentFilterSeverityResult hate, ContentFilterSeverityResult violence, ContentFilterSeverityResult selfHarm, ContentFilterDetectionResult profanity, ContentFilterBlocklistResult customBlocklists, InternalAzureContentFilterResultForPromptContentFilterResultsError error, ContentFilterDetectionResult protectedMaterialText, ContentFilterProtectedMaterialResult protectedMaterialCode, IDictionary serializedAdditionalRawData) - { - Sexual = sexual; - Hate = hate; - Violence = violence; - SelfHarm = selfHarm; - Profanity = profanity; - CustomBlocklists = customBlocklists; - Error = error; - ProtectedMaterialText = protectedMaterialText; - ProtectedMaterialCode = protectedMaterialCode; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// - /// A content filter category for language related to anatomical organs and genitals, romantic relationships, acts - /// portrayed in erotic or affectionate terms, pregnancy, physical sexual acts, including those portrayed as an - /// assault or a forced sexual violent act against one's will, prostitution, pornography, and abuse. - /// - public ContentFilterSeverityResult Sexual { get; } - /// - /// A content filter category that can refer to any content that attacks or uses pejorative or discriminatory - /// language with reference to a person or identity group based on certain differentiating attributes of these groups - /// including but not limited to race, ethnicity, nationality, gender identity and expression, sexual orientation, - /// religion, immigration status, ability status, personal appearance, and body size. - /// - public ContentFilterSeverityResult Hate { get; } - /// - /// A content filter category for language related to physical actions intended to hurt, injure, damage, or kill - /// someone or something; describes weapons, guns and related entities, such as manufactures, associations, - /// legislation, and so on. - /// - public ContentFilterSeverityResult Violence { get; } - /// - /// A content filter category that describes language related to physical actions intended to purposely hurt, injure, - /// damage one's body or kill oneself. - /// - public ContentFilterSeverityResult SelfHarm { get; } - /// - /// A detection result that identifies whether crude, vulgar, or otherwise objection language is present in the - /// content. - /// - public ContentFilterDetectionResult Profanity { get; } - /// A collection of binary filtering outcomes for configured custom blocklists. - public ContentFilterBlocklistResult CustomBlocklists { get; } - /// A detection result that describes a match against text protected under copyright or other status. - public ContentFilterDetectionResult ProtectedMaterialText { get; } - /// A detection result that describes a match against licensed code or other protected source material. - public ContentFilterProtectedMaterialResult ProtectedMaterialCode { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseImageContentFilterResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseImageContentFilterResult.cs deleted file mode 100644 index 2a5b21055925..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/ResponseImageContentFilterResult.cs +++ /dev/null @@ -1,105 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// A content filter result for an image generation operation's output response content. - public partial class ResponseImageContentFilterResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - internal IDictionary SerializedAdditionalRawData { get; set; } - /// Initializes a new instance of . - internal ResponseImageContentFilterResult() - { - } - - /// Initializes a new instance of . - /// - /// A content filter category for language related to anatomical organs and genitals, romantic relationships, acts - /// portrayed in erotic or affectionate terms, pregnancy, physical sexual acts, including those portrayed as an - /// assault or a forced sexual violent act against one's will, prostitution, pornography, and abuse. - /// - /// - /// A content filter category for language related to physical actions intended to hurt, injure, damage, or kill - /// someone or something; describes weapons, guns and related entities, such as manufactures, associations, - /// legislation, and so on. - /// - /// - /// A content filter category that can refer to any content that attacks or uses pejorative or discriminatory - /// language with reference to a person or identity group based on certain differentiating attributes of these groups - /// including but not limited to race, ethnicity, nationality, gender identity and expression, sexual orientation, - /// religion, immigration status, ability status, personal appearance, and body size. - /// - /// - /// A content filter category that describes language related to physical actions intended to purposely hurt, injure, - /// damage one's body or kill oneself. - /// - /// Keeps track of any properties unknown to the library. - internal ResponseImageContentFilterResult(ContentFilterSeverityResult sexual, ContentFilterSeverityResult violence, ContentFilterSeverityResult hate, ContentFilterSeverityResult selfHarm, IDictionary serializedAdditionalRawData) - { - Sexual = sexual; - Violence = violence; - Hate = hate; - SelfHarm = selfHarm; - SerializedAdditionalRawData = serializedAdditionalRawData; - } - - /// - /// A content filter category for language related to anatomical organs and genitals, romantic relationships, acts - /// portrayed in erotic or affectionate terms, pregnancy, physical sexual acts, including those portrayed as an - /// assault or a forced sexual violent act against one's will, prostitution, pornography, and abuse. - /// - public ContentFilterSeverityResult Sexual { get; } - /// - /// A content filter category for language related to physical actions intended to hurt, injure, damage, or kill - /// someone or something; describes weapons, guns and related entities, such as manufactures, associations, - /// legislation, and so on. - /// - public ContentFilterSeverityResult Violence { get; } - /// - /// A content filter category that can refer to any content that attacks or uses pejorative or discriminatory - /// language with reference to a person or identity group based on certain differentiating attributes of these groups - /// including but not limited to race, ethnicity, nationality, gender identity and expression, sexual orientation, - /// religion, immigration status, ability status, personal appearance, and body size. - /// - public ContentFilterSeverityResult Hate { get; } - /// - /// A content filter category that describes language related to physical actions intended to purposely hurt, injure, - /// damage one's body or kill oneself. - /// - public ContentFilterSeverityResult SelfHarm { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.Serialization.cs new file mode 100644 index 000000000000..d3db8e2ebef5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.Serialization.cs @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class SpeechGenerationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(SpeechGenerationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("input"u8); + writer.WriteStringValue(Input); + writer.WritePropertyName("voice"u8); + writer.WriteStringValue(Voice.ToString()); + if (Optional.IsDefined(ResponseFormat)) + { + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); + } + if (Optional.IsDefined(Speed)) + { + writer.WritePropertyName("speed"u8); + writer.WriteNumberValue(Speed.Value); + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + SpeechGenerationOptions 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(SpeechGenerationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSpeechGenerationOptions(document.RootElement, options); + } + + internal static SpeechGenerationOptions DeserializeSpeechGenerationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string input = default; + SpeechVoice voice = default; + SpeechGenerationResponseFormat? responseFormat = default; + float? speed = default; + string model = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("input"u8)) + { + input = property.Value.GetString(); + continue; + } + if (property.NameEquals("voice"u8)) + { + voice = new SpeechVoice(property.Value.GetString()); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = new SpeechGenerationResponseFormat(property.Value.GetString()); + continue; + } + if (property.NameEquals("speed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + speed = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SpeechGenerationOptions( + input, + voice, + responseFormat, + speed, + model, + serializedAdditionalRawData); + } + + 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(SpeechGenerationOptions)} does not support writing '{options.Format}' format."); + } + } + + SpeechGenerationOptions 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 DeserializeSpeechGenerationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SpeechGenerationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SpeechGenerationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeSpeechGenerationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.cs new file mode 100644 index 000000000000..21f6b6fd2888 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of the request options that control the behavior of a text-to-speech operation. + public partial class SpeechGenerationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The text to generate audio for. The maximum length is 4096 characters. + /// The voice to use for text-to-speech. + /// is null. + public SpeechGenerationOptions(string input, SpeechVoice voice) + { + Argument.AssertNotNull(input, nameof(input)); + + Input = input; + Voice = voice; + } + + /// Initializes a new instance of . + /// The text to generate audio for. The maximum length is 4096 characters. + /// The voice to use for text-to-speech. + /// The audio output format for the spoken text. By default, the MP3 format will be used. + /// The speed of speech for generated audio. Values are valid in the range from 0.25 to 4.0, with 1.0 the default and higher values corresponding to faster speech. + /// The model to use for this text-to-speech request. + /// Keeps track of any properties unknown to the library. + internal SpeechGenerationOptions(string input, SpeechVoice voice, SpeechGenerationResponseFormat? responseFormat, float? speed, string deploymentName, IDictionary serializedAdditionalRawData) + { + Input = input; + Voice = voice; + ResponseFormat = responseFormat; + Speed = speed; + DeploymentName = deploymentName; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SpeechGenerationOptions() + { + } + + /// The text to generate audio for. The maximum length is 4096 characters. + public string Input { get; } + /// The voice to use for text-to-speech. + public SpeechVoice Voice { get; } + /// The audio output format for the spoken text. By default, the MP3 format will be used. + public SpeechGenerationResponseFormat? ResponseFormat { get; set; } + /// The speed of speech for generated audio. Values are valid in the range from 0.25 to 4.0, with 1.0 the default and higher values corresponding to faster speech. + public float? Speed { get; set; } + /// The model to use for this text-to-speech request. + public string DeploymentName { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationResponseFormat.cs new file mode 100644 index 000000000000..e2af864d093b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationResponseFormat.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The supported audio output formats for text-to-speech. + public readonly partial struct SpeechGenerationResponseFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public SpeechGenerationResponseFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string Mp3Value = "mp3"; + private const string OpusValue = "opus"; + private const string AacValue = "aac"; + private const string FlacValue = "flac"; + private const string WavValue = "wav"; + private const string PcmValue = "pcm"; + + /// Use MP3 as the audio output format. MP3 is the default, general-purpose format. + public static SpeechGenerationResponseFormat Mp3 { get; } = new SpeechGenerationResponseFormat(Mp3Value); + /// Use Opus as the audio output format. Opus is optimized for internet streaming and low latency. + public static SpeechGenerationResponseFormat Opus { get; } = new SpeechGenerationResponseFormat(OpusValue); + /// Use AAC as the audio output format. AAC is optimized for digital audio compression and is preferred by YouTube, Android, and iOS. + public static SpeechGenerationResponseFormat Aac { get; } = new SpeechGenerationResponseFormat(AacValue); + /// Use FLAC as the audio output format. FLAC is a fully lossless format optimized for maximum quality at the expense of size. + public static SpeechGenerationResponseFormat Flac { get; } = new SpeechGenerationResponseFormat(FlacValue); + /// Use uncompressed WAV as the audio output format, suitable for low-latency applications to avoid decoding overhead. + public static SpeechGenerationResponseFormat Wav { get; } = new SpeechGenerationResponseFormat(WavValue); + /// Use uncompressed PCM as the audio output format, which is similar to WAV but contains raw samples in 24kHz (16-bit signed, low-endian), without the header. + public static SpeechGenerationResponseFormat Pcm { get; } = new SpeechGenerationResponseFormat(PcmValue); + /// Determines if two values are the same. + public static bool operator ==(SpeechGenerationResponseFormat left, SpeechGenerationResponseFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(SpeechGenerationResponseFormat left, SpeechGenerationResponseFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator SpeechGenerationResponseFormat(string value) => new SpeechGenerationResponseFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is SpeechGenerationResponseFormat other && Equals(other); + /// + public bool Equals(SpeechGenerationResponseFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechVoice.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechVoice.cs new file mode 100644 index 000000000000..a4b9c07a167f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechVoice.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The available voices for text-to-speech. + public readonly partial struct SpeechVoice : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public SpeechVoice(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AlloyValue = "alloy"; + private const string EchoValue = "echo"; + private const string FableValue = "fable"; + private const string OnyxValue = "onyx"; + private const string NovaValue = "nova"; + private const string ShimmerValue = "shimmer"; + + /// The Alloy voice. + public static SpeechVoice Alloy { get; } = new SpeechVoice(AlloyValue); + /// The Echo voice. + public static SpeechVoice Echo { get; } = new SpeechVoice(EchoValue); + /// The Fable voice. + public static SpeechVoice Fable { get; } = new SpeechVoice(FableValue); + /// The Onyx voice. + public static SpeechVoice Onyx { get; } = new SpeechVoice(OnyxValue); + /// The Nova voice. + public static SpeechVoice Nova { get; } = new SpeechVoice(NovaValue); + /// The Shimmer voice. + public static SpeechVoice Shimmer { get; } = new SpeechVoice(ShimmerValue); + /// Determines if two values are the same. + public static bool operator ==(SpeechVoice left, SpeechVoice right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(SpeechVoice left, SpeechVoice right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator SpeechVoice(string value) => new SpeechVoice(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is SpeechVoice other && Equals(other); + /// + public bool Equals(SpeechVoice other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..2a797b740019 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownAzureChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(AzureChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + AzureChatExtensionConfiguration 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(AzureChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatExtensionConfiguration(document.RootElement, options); + } + + internal static UnknownAzureChatExtensionConfiguration DeserializeUnknownAzureChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureChatExtensionType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownAzureChatExtensionConfiguration(type, serializedAdditionalRawData); + } + + 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(AzureChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureChatExtensionConfiguration 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 DeserializeAzureChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownAzureChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownAzureChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.cs new file mode 100644 index 000000000000..c9f09702aa3a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.cs @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of AzureChatExtensionConfiguration. + internal partial class UnknownAzureChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + internal UnknownAzureChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownAzureChatExtensionConfiguration() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.Serialization.cs new file mode 100644 index 000000000000..54e661b18f0f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownChatCompletionsNamedToolSelection : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsNamedToolSelection)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsNamedToolSelection 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(ChatCompletionsNamedToolSelection)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsNamedToolSelection(document.RootElement, options); + } + + internal static UnknownChatCompletionsNamedToolSelection DeserializeUnknownChatCompletionsNamedToolSelection(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownChatCompletionsNamedToolSelection(type, serializedAdditionalRawData); + } + + 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(ChatCompletionsNamedToolSelection)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsNamedToolSelection 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 DeserializeChatCompletionsNamedToolSelection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsNamedToolSelection)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatCompletionsNamedToolSelection FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownChatCompletionsNamedToolSelection(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.cs new file mode 100644 index 000000000000..f3a885278854 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatCompletionsNamedToolSelection. + internal partial class UnknownChatCompletionsNamedToolSelection : ChatCompletionsNamedToolSelection + { + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal UnknownChatCompletionsNamedToolSelection(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatCompletionsNamedToolSelection() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.Serialization.cs new file mode 100644 index 000000000000..eae4d2f85468 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownChatCompletionsResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsResponseFormat)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsResponseFormat 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(ChatCompletionsResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsResponseFormat(document.RootElement, options); + } + + internal static UnknownChatCompletionsResponseFormat DeserializeUnknownChatCompletionsResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownChatCompletionsResponseFormat(type, serializedAdditionalRawData); + } + + 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(ChatCompletionsResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsResponseFormat 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 DeserializeChatCompletionsResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatCompletionsResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownChatCompletionsResponseFormat(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.cs new file mode 100644 index 000000000000..1b7ad649a682 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatCompletionsResponseFormat. + internal partial class UnknownChatCompletionsResponseFormat : ChatCompletionsResponseFormat + { + /// Initializes a new instance of . + /// The discriminated type for the response format. + /// Keeps track of any properties unknown to the library. + internal UnknownChatCompletionsResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatCompletionsResponseFormat() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.Serialization.cs similarity index 62% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.Serialization.cs index dd67f9ec7c3e..8af7d6bd1d11 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.Serialization.cs @@ -11,23 +11,25 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.OpenAI.Assistants +namespace Azure.AI.OpenAI { - public partial class RetrievalToolDefinition : IUtf8JsonSerializable, IJsonModel + internal partial class UnknownChatCompletionsToolCall : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - 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(RetrievalToolDefinition)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support writing '{format}' format."); } writer.WriteStartObject(); writer.WritePropertyName("type"u8); writer.WriteStringValue(Type); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -46,19 +48,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade writer.WriteEndObject(); } - RetrievalToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatCompletionsToolCall 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(RetrievalToolDefinition)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeRetrievalToolDefinition(document.RootElement, options); + return DeserializeChatCompletionsToolCall(document.RootElement, options); } - internal static RetrievalToolDefinition DeserializeRetrievalToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownChatCompletionsToolCall DeserializeUnknownChatCompletionsToolCall(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -66,7 +68,8 @@ internal static RetrievalToolDefinition DeserializeRetrievalToolDefinition(JsonE { return null; } - string type = default; + string type = "Unknown"; + string id = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -76,59 +79,64 @@ internal static RetrievalToolDefinition DeserializeRetrievalToolDefinition(JsonE type = property.Value.GetString(); continue; } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new RetrievalToolDefinition(type, serializedAdditionalRawData); + return new UnknownChatCompletionsToolCall(type, id, 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(RetrievalToolDefinition)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support writing '{options.Format}' format."); } } - RetrievalToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ChatCompletionsToolCall 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 DeserializeRetrievalToolDefinition(document.RootElement, options); + return DeserializeChatCompletionsToolCall(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(RetrievalToolDefinition)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static new RetrievalToolDefinition FromResponse(Response response) + internal static new UnknownChatCompletionsToolCall FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeRetrievalToolDefinition(document.RootElement); + return DeserializeUnknownChatCompletionsToolCall(document.RootElement); } /// Convert into a . internal override RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.cs new file mode 100644 index 000000000000..88be20fa0524 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatCompletionsToolCall. + internal partial class UnknownChatCompletionsToolCall : ChatCompletionsToolCall + { + /// Initializes a new instance of . + /// The object type. + /// The ID of the tool call. + /// Keeps track of any properties unknown to the library. + internal UnknownChatCompletionsToolCall(string type, string id, IDictionary serializedAdditionalRawData) : base(type, id, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatCompletionsToolCall() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.Serialization.cs new file mode 100644 index 000000000000..a858ba0d3fb0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownChatCompletionsToolDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatCompletionsToolDefinition)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatCompletionsToolDefinition 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(ChatCompletionsToolDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsToolDefinition(document.RootElement, options); + } + + internal static UnknownChatCompletionsToolDefinition DeserializeUnknownChatCompletionsToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownChatCompletionsToolDefinition(type, serializedAdditionalRawData); + } + + 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(ChatCompletionsToolDefinition)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsToolDefinition 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 DeserializeChatCompletionsToolDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsToolDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatCompletionsToolDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownChatCompletionsToolDefinition(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.cs new file mode 100644 index 000000000000..5b671919dd47 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatCompletionsToolDefinition. + internal partial class UnknownChatCompletionsToolDefinition : ChatCompletionsToolDefinition + { + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal UnknownChatCompletionsToolDefinition(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatCompletionsToolDefinition() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.Serialization.cs similarity index 50% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSource.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.Serialization.cs index bb4da7e040a3..41d2676b1bc6 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/InternalUnknownAzureChatDataSource.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.Serialization.cs @@ -1,39 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI.Chat +namespace Azure.AI.OpenAI { - internal partial class InternalUnknownAzureChatDataSource : IJsonModel + internal partial class UnknownChatMessageContentItem : IUtf8JsonSerializable, IJsonModel { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatDataSource)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support writing '{format}' format."); } writer.WriteStartObject(); - if (SerializedAdditionalRawData?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (SerializedAdditionalRawData != null) + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) { - foreach (var item in SerializedAdditionalRawData) + foreach (var item in _serializedAdditionalRawData) { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } writer.WritePropertyName(item.Key); #if NET6_0_OR_GREATER writer.WriteRawValue(item.Value); @@ -48,19 +46,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOp writer.WriteEndObject(); } - ChatDataSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatMessageContentItem 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(ChatDataSource)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatDataSource(document.RootElement, options); + return DeserializeChatMessageContentItem(document.RootElement, options); } - internal static InternalUnknownAzureChatDataSource DeserializeInternalUnknownAzureChatDataSource(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownChatMessageContentItem DeserializeUnknownChatMessageContentItem(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -80,58 +78,58 @@ internal static InternalUnknownAzureChatDataSource DeserializeInternalUnknownAzu } if (options.Format != "W") { - rawDataDictionary ??= new Dictionary(); rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new InternalUnknownAzureChatDataSource(type, serializedAdditionalRawData); + return new UnknownChatMessageContentItem(type, 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(ChatDataSource)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support writing '{options.Format}' format."); } } - ChatDataSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ChatMessageContentItem 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 DeserializeChatDataSource(document.RootElement, options); + return DeserializeChatMessageContentItem(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ChatDataSource)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. - /// The result to deserialize the model from. - internal static new InternalUnknownAzureChatDataSource FromResponse(PipelineResponse response) + /// The response to deserialize the model from. + internal static new UnknownChatMessageContentItem FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content); - return DeserializeInternalUnknownAzureChatDataSource(document.RootElement); + return DeserializeUnknownChatMessageContentItem(document.RootElement); } - /// Convert into a . - internal override BinaryContent ToBinaryContent() + /// Convert into a . + internal override RequestContent ToRequestContent() { - return BinaryContent.Create(this, ModelSerializationExtensions.WireOptions); + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; } } } - diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.cs new file mode 100644 index 000000000000..7407e7520c34 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatMessageContentItem. + internal partial class UnknownChatMessageContentItem : ChatMessageContentItem + { + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + internal UnknownChatMessageContentItem(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatMessageContentItem() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.Serialization.cs new file mode 100644 index 000000000000..1318dcfb89db --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownChatRequestMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(ChatRequestMessage)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + ChatRequestMessage 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(ChatRequestMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestMessage(document.RootElement, options); + } + + internal static UnknownChatRequestMessage DeserializeUnknownChatRequestMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatRole role = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownChatRequestMessage(role, serializedAdditionalRawData); + } + + 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(ChatRequestMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestMessage 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 DeserializeChatRequestMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatRequestMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownChatRequestMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.cs new file mode 100644 index 000000000000..16ce3943613b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatRequestMessage. + internal partial class UnknownChatRequestMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + internal UnknownChatRequestMessage(ChatRole role, IDictionary serializedAdditionalRawData) : base(role, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatRequestMessage() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..182251a16716 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownOnYourDataAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataAuthenticationOptions 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(OnYourDataAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataAuthenticationOptions(document.RootElement, options); + } + + internal static UnknownOnYourDataAuthenticationOptions DeserializeUnknownOnYourDataAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OnYourDataAuthenticationType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownOnYourDataAuthenticationOptions(type, serializedAdditionalRawData); + } + + 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(OnYourDataAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataAuthenticationOptions 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 DeserializeOnYourDataAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownOnYourDataAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownOnYourDataAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.cs new file mode 100644 index 000000000000..3d47c4f32f51 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of OnYourDataAuthenticationOptions. + internal partial class UnknownOnYourDataAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + internal UnknownOnYourDataAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownOnYourDataAuthenticationOptions() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..019071860dd7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownOnYourDataVectorSearchAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataVectorSearchAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataVectorSearchAuthenticationOptions 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(OnYourDataVectorSearchAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorSearchAuthenticationOptions(document.RootElement, options); + } + + internal static UnknownOnYourDataVectorSearchAuthenticationOptions DeserializeUnknownOnYourDataVectorSearchAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OnYourDataVectorSearchAuthenticationType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorSearchAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownOnYourDataVectorSearchAuthenticationOptions(type, serializedAdditionalRawData); + } + + 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(OnYourDataVectorSearchAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorSearchAuthenticationOptions 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 DeserializeOnYourDataVectorSearchAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownOnYourDataVectorSearchAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownOnYourDataVectorSearchAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.cs new file mode 100644 index 000000000000..13d87a07efb2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of OnYourDataVectorSearchAuthenticationOptions. + internal partial class UnknownOnYourDataVectorSearchAuthenticationOptions : OnYourDataVectorSearchAuthenticationOptions + { + /// Initializes a new instance of . + /// The type of authentication to use. + /// Keeps track of any properties unknown to the library. + internal UnknownOnYourDataVectorSearchAuthenticationOptions(OnYourDataVectorSearchAuthenticationType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownOnYourDataVectorSearchAuthenticationOptions() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..db021dc1f917 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownOnYourDataVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(OnYourDataVectorizationSource)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + OnYourDataVectorizationSource 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(OnYourDataVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorizationSource(document.RootElement, options); + } + + internal static UnknownOnYourDataVectorizationSource DeserializeUnknownOnYourDataVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OnYourDataVectorizationSourceType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorizationSourceType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownOnYourDataVectorizationSource(type, serializedAdditionalRawData); + } + + 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(OnYourDataVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorizationSource 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 DeserializeOnYourDataVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownOnYourDataVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUnknownOnYourDataVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.cs new file mode 100644 index 000000000000..2bf5702ab3fd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of OnYourDataVectorizationSource. + internal partial class UnknownOnYourDataVectorizationSource : OnYourDataVectorizationSource + { + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + internal UnknownOnYourDataVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownOnYourDataVectorizationSource() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.Serialization.cs new file mode 100644 index 000000000000..a453778dce17 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.Serialization.cs @@ -0,0 +1,231 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class Upload : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(Upload)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + writer.WritePropertyName("bytes"u8); + writer.WriteNumberValue(Bytes); + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose.ToString()); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + writer.WritePropertyName("expires_at"u8); + writer.WriteNumberValue(ExpiresAt, "U"); + if (Optional.IsDefined(Object)) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.Value.ToString()); + } + if (Optional.IsDefined(File)) + { + if (File != null) + { + writer.WritePropertyName("file"u8); + writer.WriteObjectValue(File, options); + } + else + { + writer.WriteNull("file"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + Upload 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(Upload)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUpload(document.RootElement, options); + } + + internal static Upload DeserializeUpload(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset createdAt = default; + string filename = default; + long bytes = default; + UploadPurpose purpose = default; + UploadStatus status = default; + DateTimeOffset expiresAt = default; + UploadObject? @object = default; + OpenAIFile file = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("bytes"u8)) + { + bytes = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("purpose"u8)) + { + purpose = new UploadPurpose(property.Value.GetString()); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new UploadStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("expires_at"u8)) + { + expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("object"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + @object = new UploadObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("file"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + file = null; + continue; + } + file = OpenAIFile.DeserializeOpenAIFile(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Upload( + id, + createdAt, + filename, + bytes, + purpose, + status, + expiresAt, + @object, + file, + serializedAdditionalRawData); + } + + 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(Upload)} does not support writing '{options.Format}' format."); + } + } + + Upload 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 DeserializeUpload(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Upload)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static Upload FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUpload(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.cs new file mode 100644 index 000000000000..ac29382c966a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The Upload object can accept byte chunks in the form of Parts. + public partial class Upload + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The Upload unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// The name of the file to be uploaded. + /// The intended number of bytes to be uploaded. + /// The intended purpose of the file. + /// The status of the Upload. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// or is null. + internal Upload(string id, DateTimeOffset createdAt, string filename, long bytes, UploadPurpose purpose, UploadStatus status, DateTimeOffset expiresAt) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(filename, nameof(filename)); + + Id = id; + CreatedAt = createdAt; + Filename = filename; + Bytes = bytes; + Purpose = purpose; + Status = status; + ExpiresAt = expiresAt; + } + + /// Initializes a new instance of . + /// The Upload unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// The name of the file to be uploaded. + /// The intended number of bytes to be uploaded. + /// The intended purpose of the file. + /// The status of the Upload. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// The object type, which is always "upload". + /// The ready File object after the Upload is completed. + /// Keeps track of any properties unknown to the library. + internal Upload(string id, DateTimeOffset createdAt, string filename, long bytes, UploadPurpose purpose, UploadStatus status, DateTimeOffset expiresAt, UploadObject? @object, OpenAIFile file, IDictionary serializedAdditionalRawData) + { + Id = id; + CreatedAt = createdAt; + Filename = filename; + Bytes = bytes; + Purpose = purpose; + Status = status; + ExpiresAt = expiresAt; + Object = @object; + File = file; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Upload() + { + } + + /// The Upload unique identifier, which can be referenced in API endpoints. + public string Id { get; } + /// The Unix timestamp (in seconds) for when the Upload was created. + public DateTimeOffset CreatedAt { get; } + /// The name of the file to be uploaded. + public string Filename { get; } + /// The intended number of bytes to be uploaded. + public long Bytes { get; } + /// The intended purpose of the file. + public UploadPurpose Purpose { get; } + /// The status of the Upload. + public UploadStatus Status { get; } + /// The Unix timestamp (in seconds) for when the Upload was created. + public DateTimeOffset ExpiresAt { get; } + /// The object type, which is always "upload". + public UploadObject? Object { get; } + /// The ready File object after the Upload is completed. + public OpenAIFile File { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.Serialization.cs new file mode 100644 index 000000000000..d0fba1b9ef17 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.Serialization.cs @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UploadFileRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(UploadFileRequest)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("file"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(Data)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(Data))) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose.ToString()); + if (Optional.IsDefined(Filename)) + { + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + UploadFileRequest 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(UploadFileRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUploadFileRequest(document.RootElement, options); + } + + internal static UploadFileRequest DeserializeUploadFileRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Stream file = default; + FilePurpose purpose = default; + string filename = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file"u8)) + { + file = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (property.NameEquals("purpose"u8)) + { + purpose = new FilePurpose(property.Value.GetString()); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UploadFileRequest(file, purpose, filename, serializedAdditionalRawData); + } + + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataRequestContent content = ToMultipartRequestContent(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() + { + MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); + content.Add(Data, "file", "file", "application/octet-stream"); + content.Add(Purpose.ToString(), "purpose"); + if (Optional.IsDefined(Filename)) + { + content.Add(Filename, "filename"); + } + return content; + } + + 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); + case "MFD": + return SerializeMultipart(options); + default: + throw new FormatException($"The model {nameof(UploadFileRequest)} does not support writing '{options.Format}' format."); + } + } + + UploadFileRequest 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 DeserializeUploadFileRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UploadFileRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UploadFileRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUploadFileRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.cs new file mode 100644 index 000000000000..a39f8a840ef4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; + +namespace Azure.AI.OpenAI +{ + /// The UploadFileRequest. + internal partial class UploadFileRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The file data (not filename) to upload. + /// The intended purpose of the file. + /// is null. + internal UploadFileRequest(Stream data, FilePurpose purpose) + { + Argument.AssertNotNull(data, nameof(data)); + + Data = data; + Purpose = purpose; + } + + /// Initializes a new instance of . + /// The file data (not filename) to upload. + /// The intended purpose of the file. + /// A filename to associate with the uploaded data. + /// Keeps track of any properties unknown to the library. + internal UploadFileRequest(Stream data, FilePurpose purpose, string filename, IDictionary serializedAdditionalRawData) + { + Data = data; + Purpose = purpose; + Filename = filename; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal UploadFileRequest() + { + } + + /// The file data (not filename) to upload. + public Stream Data { get; } + /// The intended purpose of the file. + public FilePurpose Purpose { get; } + /// A filename to associate with the uploaded data. + public string Filename { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadObject.cs new file mode 100644 index 000000000000..649a57ce5a4c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The Upload_object. + public readonly partial struct UploadObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public UploadObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UploadValue = "upload"; + + /// upload. + public static UploadObject Upload { get; } = new UploadObject(UploadValue); + /// Determines if two values are the same. + public static bool operator ==(UploadObject left, UploadObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(UploadObject left, UploadObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator UploadObject(string value) => new UploadObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is UploadObject other && Equals(other); + /// + public bool Equals(UploadObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.Serialization.cs new file mode 100644 index 000000000000..62b0a1e9de71 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.Serialization.cs @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class UploadPart : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + 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(UploadPart)} does not support writing '{format}' format."); + } + + writer.WriteStartObject(); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("upload_id"u8); + writer.WriteStringValue(UploadId); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (Optional.IsDefined(AzureBlockId)) + { + writer.WritePropertyName("azure_block_id"u8); + writer.WriteStringValue(AzureBlockId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + 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(); + } + + UploadPart 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(UploadPart)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUploadPart(document.RootElement, options); + } + + internal static UploadPart DeserializeUploadPart(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset createdAt = default; + string uploadId = default; + UploadPartObject @object = default; + string azureBlockId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("upload_id"u8)) + { + uploadId = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new UploadPartObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("azure_block_id"u8)) + { + azureBlockId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UploadPart( + id, + createdAt, + uploadId, + @object, + azureBlockId, + serializedAdditionalRawData); + } + + 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(UploadPart)} does not support writing '{options.Format}' format."); + } + } + + UploadPart 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 DeserializeUploadPart(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UploadPart)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UploadPart FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content); + return DeserializeUploadPart(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.cs new file mode 100644 index 000000000000..2706e3f8f9cc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The upload Part represents a chunk of bytes we can add to an Upload object. + public partial class UploadPart + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The upload Part unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Part was created. + /// The ID of the Upload object that this Part was added to. + /// or is null. + internal UploadPart(string id, DateTimeOffset createdAt, string uploadId) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); + + Id = id; + CreatedAt = createdAt; + UploadId = uploadId; + } + + /// Initializes a new instance of . + /// The upload Part unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Part was created. + /// The ID of the Upload object that this Part was added to. + /// The object type, which is always `upload.part`. + /// Azure only field. + /// Keeps track of any properties unknown to the library. + internal UploadPart(string id, DateTimeOffset createdAt, string uploadId, UploadPartObject @object, string azureBlockId, IDictionary serializedAdditionalRawData) + { + Id = id; + CreatedAt = createdAt; + UploadId = uploadId; + Object = @object; + AzureBlockId = azureBlockId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal UploadPart() + { + } + + /// The upload Part unique identifier, which can be referenced in API endpoints. + public string Id { get; } + /// The Unix timestamp (in seconds) for when the Part was created. + public DateTimeOffset CreatedAt { get; } + /// The ID of the Upload object that this Part was added to. + public string UploadId { get; } + /// The object type, which is always `upload.part`. + public UploadPartObject Object { get; } = UploadPartObject.UploadPart; + + /// Azure only field. + public string AzureBlockId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPartObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPartObject.cs new file mode 100644 index 000000000000..d161f3e609de --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPartObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The UploadPart_object. + public readonly partial struct UploadPartObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public UploadPartObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UploadPartValue = "upload.part"; + + /// upload.part. + public static UploadPartObject UploadPart { get; } = new UploadPartObject(UploadPartValue); + /// Determines if two values are the same. + public static bool operator ==(UploadPartObject left, UploadPartObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(UploadPartObject left, UploadPartObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator UploadPartObject(string value) => new UploadPartObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is UploadPartObject other && Equals(other); + /// + public bool Equals(UploadPartObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPurpose.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPurpose.cs new file mode 100644 index 000000000000..69f7e4ccfb6b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPurpose.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The UploadPurpose. + public readonly partial struct UploadPurpose : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public UploadPurpose(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string BatchValue = "batch"; + private const string BatchOutputValue = "batch_output"; + private const string FineTuneValue = "fine-tune"; + private const string FineTuneResultsValue = "fine-tune-results"; + private const string AssistantsValue = "assistants"; + private const string AssistantsOutputValue = "assistants_output"; + private const string VisionValue = "vision"; + + /// batch. + public static UploadPurpose Batch { get; } = new UploadPurpose(BatchValue); + /// batch_output. + public static UploadPurpose BatchOutput { get; } = new UploadPurpose(BatchOutputValue); + /// fine-tune. + public static UploadPurpose FineTune { get; } = new UploadPurpose(FineTuneValue); + /// fine-tune-results. + public static UploadPurpose FineTuneResults { get; } = new UploadPurpose(FineTuneResultsValue); + /// assistants. + public static UploadPurpose Assistants { get; } = new UploadPurpose(AssistantsValue); + /// assistants_output. + public static UploadPurpose AssistantsOutput { get; } = new UploadPurpose(AssistantsOutputValue); + /// vision. + public static UploadPurpose Vision { get; } = new UploadPurpose(VisionValue); + /// Determines if two values are the same. + public static bool operator ==(UploadPurpose left, UploadPurpose right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(UploadPurpose left, UploadPurpose right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator UploadPurpose(string value) => new UploadPurpose(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is UploadPurpose other && Equals(other); + /// + public bool Equals(UploadPurpose other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadStatus.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadStatus.cs new file mode 100644 index 000000000000..bdb03110818d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadStatus.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The UploadStatus. + public readonly partial struct UploadStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public UploadStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string PendingValue = "pending"; + private const string CompletedValue = "completed"; + private const string CancelledValue = "cancelled"; + private const string ExpiredValue = "expired"; + + /// pending. + public static UploadStatus Pending { get; } = new UploadStatus(PendingValue); + /// completed. + public static UploadStatus Completed { get; } = new UploadStatus(CompletedValue); + /// cancelled. + public static UploadStatus Cancelled { get; } = new UploadStatus(CancelledValue); + /// expired. + public static UploadStatus Expired { get; } = new UploadStatus(ExpiredValue); + /// Determines if two values are the same. + public static bool operator ==(UploadStatus left, UploadStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(UploadStatus left, UploadStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator UploadStatus(string value) => new UploadStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is UploadStatus other && Equals(other); + /// + public bool Equals(UploadStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/tsp-location.yaml b/sdk/openai/Azure.AI.OpenAI/tsp-location.yaml new file mode 100644 index 000000000000..955ea883ccf2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/cognitiveservices/OpenAI.Inference +commit: cc338f96a11ef2749b5cdf4a1ec0b69208763cc9 +repo: Azure/azure-rest-api-specs +additionalDirectories: