diff --git a/sdk/ai/Azure.AI.Projects.OneDP/Azure.AI.Projects.OneDP.sln b/sdk/ai/Azure.AI.Projects.OneDP/Azure.AI.Projects.OneDP.sln new file mode 100644 index 000000000000..2df9b830370b --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/Azure.AI.Projects.OneDP.sln @@ -0,0 +1,54 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core.TestFramework", "..\..\core\Azure.Core.TestFramework\src\Azure.Core.TestFramework.csproj", "{ECC730C1-4AEA-420C-916A-66B19B79E4DC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.AI.Projects.OneDP", "src\Azure.AI.Projects.OneDP.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.Build.0 = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.Build.0 = Release|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.Build.0 = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.Build.0 = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.Build.0 = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.Build.0 = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.Build.0 = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/sdk/ai/Azure.AI.Projects.OneDP/CHANGELOG.md b/sdk/ai/Azure.AI.Projects.OneDP/CHANGELOG.md new file mode 100644 index 000000000000..8b33f0fedccc --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/CHANGELOG.md @@ -0,0 +1,11 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes \ No newline at end of file diff --git a/sdk/ai/Azure.AI.Projects.OneDP/Directory.Build.props b/sdk/ai/Azure.AI.Projects.OneDP/Directory.Build.props new file mode 100644 index 000000000000..63bd836ad44b --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/ai/Azure.AI.Projects.OneDP/README.md b/sdk/ai/Azure.AI.Projects.OneDP/README.md new file mode 100644 index 000000000000..20b92c86af3c --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/README.md @@ -0,0 +1,107 @@ +# Azure.AI.Projects.OneDP client library for .NET + +Azure.AI.Projects.OneDP is a managed service that helps developers get secret simply and securely. + +Use the client library for to: + +* [Get secret](https://docs.microsoft.com/azure) + +[Source code][source_root] | [Package (NuGet)][package] | [API reference documentation][reference_docs] | [Product documentation][azconfig_docs] | [Samples][source_samples] + + [Source code](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/ai/Azure.AI.Projects.OneDP/src) | [Package (NuGet)](https://www.nuget.org/packages) | [API reference documentation](https://azure.github.io/azure-sdk-for-net) | [Product documentation](https://docs.microsoft.com/azure) + +## Getting started + +This section should include everything a developer needs to do to install and create their first client connection *very quickly*. + +### Install the package + +First, provide instruction for obtaining and installing the package or library. This section might include only a single line of code, like `dotnet add package package-name`, but should enable a developer to successfully install the package from NuGet, npm, or even cloning a GitHub repository. + +Install the client library for .NET with [NuGet](https://www.nuget.org/ ): + +```dotnetcli +dotnet add package Azure.AI.Projects.OneDP --prerelease +``` + +### Prerequisites + +Include a section after the install command that details any requirements that must be satisfied before a developer can [authenticate](#authenticate-the-client) and test all of the snippets in the [Examples](#examples) section. For example, for Cosmos DB: + +> You must have an [Azure subscription](https://azure.microsoft.com/free/dotnet/) and [Cosmos DB account](https://docs.microsoft.com/azure/cosmos-db/account-overview) (SQL API). In order to take advantage of the C# 8.0 syntax, it is recommended that you compile using the [.NET Core SDK](https://dotnet.microsoft.com/download) 3.0 or higher with a [language version](https://docs.microsoft.com/dotnet/csharp/language-reference/configure-language-version#override-a-default) of `latest`. It is also possible to compile with the .NET Core SDK 2.1.x using a language version of `preview`. + +### Authenticate the client + +If your library requires authentication for use, such as for Azure services, include instructions and example code needed for initializing and authenticating. + +For example, include details on obtaining an account key and endpoint URI, setting environment variables for each, and initializing the client object. + +### Service API versions + +The client library targets the latest service API version by default. A client instance accepts an optional service API version parameter from its options to specify which API version service to communicate. + +#### Select a service API version + +You have the flexibility to explicitly select a supported service API version when instantiating a client by configuring its associated options. This ensures that the client can communicate with services using the specified API version. + +For example, + +```C# Snippet:CreateClientForSpecificApiVersion +Uri endpoint = new Uri(""); +DefaultAzureCredential credential = new DefaultAzureCredential(); +ClientOptions options = new ClientOptions(ClientOptions.ServiceVersion.) +var client = new Client(endpoint, credential, options); +``` + +When selecting an API version, it's important to verify that there are no breaking changes compared to the latest API version. If there are significant differences, API calls may fail due to incompatibility. + +Always ensure that the chosen API version is fully supported and operational for your specific use case and that it aligns with the service's versioning policy. + +## Key concepts + +The *Key concepts* section should describe the functionality of the main classes. Point out the most important and useful classes in the package (with links to their reference pages) and explain how those classes work together. Feel free to use bulleted lists, tables, code blocks, or even diagrams for clarity. + +Include the *Thread safety* and *Additional concepts* sections below at the end of your *Key concepts* section. You may remove or add links depending on what your library makes use of: + +### Thread safety + +We guarantee that all client instance methods are thread-safe and independent of each other ([guideline](https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-service-methods-thread-safety)). This ensures that the recommendation of reusing client instances is always safe, even across threads. + +### Additional concepts + +[Client options](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#configuring-service-clients-using-clientoptions) | +[Accessing the response](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#accessing-http-response-details-using-responset) | +[Long-running operations](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#consuming-long-running-operations-using-operationt) | +[Handling failures](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#reporting-errors-requestfailedexception) | +[Diagnostics](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md) | +[Mocking](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#mocking) | +[Client lifetime](https://devblogs.microsoft.com/azure-sdk/lifetime-management-and-thread-safety-guarantees-of-azure-sdk-net-clients/) + + +## Examples + +You can familiarize yourself with different APIs using [Samples](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Projects.OneDP/samples). + +## Troubleshooting + +Describe common errors and exceptions, how to "unpack" them if necessary, and include guidance for graceful handling and recovery. + +Provide information to help developers avoid throttling or other service-enforced errors they might encounter. For example, provide guidance and examples for using retry or connection policies in the API. + +If the package or a related package supports it, include tips for logging or enabling instrumentation to help them debug their code. + +## Next steps + +* Provide a link to additional code examples, ideally to those sitting alongside the README in the package's `/samples` directory. +* If appropriate, point users to other packages that might be useful. +* If you think there's a good chance that developers might stumble across your package in error (because they're searching for specific functionality and mistakenly think the package provides that functionality), point them to the packages they might be looking for. + +## Contributing + +This is a template, but your SDK readme should include details on how to contribute code to the repo/package. + + +[style-guide-msft]: https://docs.microsoft.com/style-guide/capitalization +[style-guide-cloud]: https://aka.ms/azsdk/cloud-style-guide + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net/sdk/ai/Azure.AI.Projects.OneDP/README.png) \ No newline at end of file diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Azure.AI.Projects.OneDP.csproj b/sdk/ai/Azure.AI.Projects.OneDP/src/Azure.AI.Projects.OneDP.csproj new file mode 100644 index 000000000000..fe2c1d298c6c --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Azure.AI.Projects.OneDP.csproj @@ -0,0 +1,20 @@ + + + This is the Azure.AI.Projects.OneDP client library for developing .NET applications with rich experience. + Azure SDK Code Generation Azure.AI.Projects.OneDP for Azure Data Plane + 1.0.0-beta.1 + Azure.AI.Projects.OneDP + $(RequiredTargetFrameworks) + true + + + + + + + + + + + + diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectClient.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectClient.cs new file mode 100644 index 000000000000..462b231f02e5 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectClient.cs @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.Projects.OneDP +{ + // Data plane generated client. + /// The AIProject service client. + public partial class AIProjectClient + { + private const string AuthorizationHeader = "Authorization"; + private readonly AzureKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + private static readonly string[] AuthorizationScopes = new string[] { "https://cognitiveservices.azure.com/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + + /// 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 AIProjectClient for mocking. + protected AIProjectClient() + { + } + + /// Initializes a new instance of AIProjectClient. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// A credential used to authenticate to an Azure Service. + /// or is null. + public AIProjectClient(Uri endpoint, AzureKeyCredential credential) : this(endpoint, credential, new AIProjectClientOptions()) + { + } + + /// Initializes a new instance of AIProjectClient. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// A credential used to authenticate to an Azure Service. + /// or is null. + public AIProjectClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new AIProjectClientOptions()) + { + } + + /// Initializes a new instance of AIProjectClient. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public AIProjectClient(Uri endpoint, AzureKeyCredential credential, AIProjectClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new AIProjectClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _keyCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new AzureKeyCredentialPolicy(_keyCredential, AuthorizationHeader, AuthorizationApiKeyPrefix) }, new ResponseClassifier()); + _endpoint = endpoint; + } + + /// Initializes a new instance of AIProjectClient. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public AIProjectClient(Uri endpoint, TokenCredential credential, AIProjectClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new AIProjectClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + } + + private Internal _cachedInternal; + private ServicePatterns _cachedServicePatterns; + + /// Initializes a new instance of Internal. + public virtual Internal GetInternalClient() + { + return Volatile.Read(ref _cachedInternal) ?? Interlocked.CompareExchange(ref _cachedInternal, new Internal(ClientDiagnostics, _pipeline, _keyCredential, _tokenCredential, _endpoint), null) ?? _cachedInternal; + } + + /// Initializes a new instance of ServicePatterns. + public virtual ServicePatterns GetServicePatternsClient() + { + return Volatile.Read(ref _cachedServicePatterns) ?? Interlocked.CompareExchange(ref _cachedServicePatterns, new ServicePatterns(ClientDiagnostics, _pipeline, _keyCredential, _tokenCredential, _endpoint), null) ?? _cachedServicePatterns; + } + + /// Initializes a new instance of Connections. + /// The API version to use for this operation. + /// is null. + public virtual Connections GetConnectionsClient(string apiVersion = "2025-05-15-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new Connections(ClientDiagnostics, _pipeline, _keyCredential, _tokenCredential, _endpoint, apiVersion); + } + + /// Initializes a new instance of Evaluations. + /// The API version to use for this operation. + /// is null. + public virtual Evaluations GetEvaluationsClient(string apiVersion = "2025-05-15-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new Evaluations(ClientDiagnostics, _pipeline, _keyCredential, _tokenCredential, _endpoint, apiVersion); + } + + /// Initializes a new instance of Datasets. + /// The API version to use for this operation. + /// is null. + public virtual Datasets GetDatasetsClient(string apiVersion = "2025-05-15-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new Datasets(ClientDiagnostics, _pipeline, _keyCredential, _tokenCredential, _endpoint, apiVersion); + } + + /// Initializes a new instance of Indexes. + /// The API version to use for this operation. + /// is null. + public virtual Indexes GetIndexesClient(string apiVersion = "2025-05-15-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new Indexes(ClientDiagnostics, _pipeline, _keyCredential, _tokenCredential, _endpoint, apiVersion); + } + + /// Initializes a new instance of Deployments. + /// The API version to use for this operation. + /// is null. + public virtual Deployments GetDeploymentsClient(string apiVersion = "2025-05-15-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new Deployments(ClientDiagnostics, _pipeline, _keyCredential, _tokenCredential, _endpoint, apiVersion); + } + + /// Initializes a new instance of RedTeams. + /// The API version to use for this operation. + /// is null. + public virtual RedTeams GetRedTeamsClient(string apiVersion = "2025-05-15-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new RedTeams(ClientDiagnostics, _pipeline, _keyCredential, _tokenCredential, _endpoint, apiVersion); + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectClientOptions.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectClientOptions.cs new file mode 100644 index 000000000000..f6707b6813f3 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectClientOptions.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + /// Client options for AIProjectClient. + public partial class AIProjectClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2025_05_15_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2025-05-01". + V2025_05_01 = 1, + /// Service version "2025-05-15-preview". + V2025_05_15_Preview = 2, + } + + internal string Version { get; } + + /// Initializes new instance of AIProjectClientOptions. + public AIProjectClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2025_05_01 => "2025-05-01", + ServiceVersion.V2025_05_15_Preview => "2025-05-15-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectsOneDPClientBuilderExtensions.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectsOneDPClientBuilderExtensions.cs new file mode 100644 index 000000000000..f8893ce70ec9 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectsOneDPClientBuilderExtensions.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure; +using Azure.AI.Projects.OneDP; +using Azure.Core.Extensions; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class AIProjectsOneDPClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// A credential used to authenticate to an Azure Service. + public static IAzureClientBuilder AddAIProjectClient(this TBuilder builder, Uri endpoint, AzureKeyCredential credential) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new AIProjectClient(endpoint, credential, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + public static IAzureClientBuilder AddAIProjectClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new AIProjectClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddAIProjectClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectsOneDPModelFactory.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectsOneDPModelFactory.cs new file mode 100644 index 000000000000..2a27a258ea16 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AIProjectsOneDPModelFactory.cs @@ -0,0 +1,417 @@ +// 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.Projects.OneDP +{ + /// Model factory for models. + public static partial class AIProjectsOneDPModelFactory + { + /// Initializes a new instance of . + /// Discriminator property for Connection. + /// The name of the resource. + /// Category of the connection. + /// The connection URL to be used for this service. + /// Whether the connection is tagged as the default connection of its type. + /// + /// The credentials used by the connection + /// 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 . + /// + /// Metadata of the connection. + /// A new instance for mocking. + public static Connection Connection(string authType = null, string name = null, ConnectionType type = default, string target = null, bool isDefault = default, BaseCredentials credentials = null, IReadOnlyDictionary metadata = null) + { + metadata ??= new Dictionary(); + + return new UnknownConnection( + authType, + name, + type, + target, + isDefault, + credentials, + metadata, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// API Key. + /// A new instance for mocking. + public static ApiKeyCredentials ApiKeyCredentials(string apiKey = null) + { + return new ApiKeyCredentials(CredentialType.ApiKey, serializedAdditionalRawData: null, apiKey); + } + + /// Initializes a new instance of . + /// SAS token. + /// A new instance for mocking. + public static SASCredentials SASCredentials(string sasToken = null) + { + return new SASCredentials(CredentialType.SAS, serializedAdditionalRawData: null, sasToken); + } + + /// Initializes a new instance of . + /// Identifier of the evaluation. + /// + /// Data for evaluation. + /// 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 . + /// + /// Display Name for evaluation. It helps to find the evaluation easily in AI Foundry. It does not need to be unique. + /// Description of the evaluation. It can be used to store additional information about the evaluation and is mutable. + /// Status of the evaluation. It is set by service and is read-only. + /// Evaluation's tags. Unlike properties, tags are fully mutable. + /// Evaluation's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// Evaluators to be used for the evaluation. + /// A new instance for mocking. + public static Evaluation Evaluation(string id = null, InputData data = null, string displayName = null, string description = null, string status = null, IDictionary tags = null, IDictionary properties = null, IDictionary evaluators = null) + { + tags ??= new Dictionary(); + properties ??= new Dictionary(); + evaluators ??= new Dictionary(); + + return new Evaluation( + id, + data, + displayName, + description, + status, + tags, + properties, + evaluators, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + /// Dataset type. + /// Indicates if dataset is reference only or managed by dataset service. If true, the underlying data will be deleted when the dataset version is deleted. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// A new instance for mocking. + public static DatasetVersion DatasetVersion(string datasetUri = null, string type = null, bool? isReference = null, string stage = null, string id = null, string name = null, string version = null, string description = null, IDictionary tags = null) + { + tags ??= new Dictionary(); + + return new UnknownDatasetVersion( + datasetUri, + type == null ? default : new DatasetType(type), + isReference, + stage, + id, + name, + version, + description, + tags, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + /// Indicates if dataset is reference only or managed by dataset service. If true, the underlying data will be deleted when the dataset version is deleted. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Indicates OpenAI Purpose. FileDatasets created with this field will be compatible with OpenAI-specific features. + /// A new instance for mocking. + public static FileDatasetVersion FileDatasetVersion(string datasetUri = null, bool? isReference = null, string stage = null, string id = null, string name = null, string version = null, string description = null, IDictionary tags = null, string openAIPurpose = null) + { + tags ??= new Dictionary(); + + return new FileDatasetVersion( + datasetUri, + DatasetType.UriFile, + isReference, + stage, + id, + name, + version, + description, + tags, + serializedAdditionalRawData: null, + openAIPurpose); + } + + /// Initializes a new instance of . + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + /// Indicates if dataset is reference only or managed by dataset service. If true, the underlying data will be deleted when the dataset version is deleted. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// A new instance for mocking. + public static FolderDatasetVersion FolderDatasetVersion(string datasetUri = null, bool? isReference = null, string stage = null, string id = null, string name = null, string version = null, string description = null, IDictionary tags = null) + { + tags ??= new Dictionary(); + + return new FolderDatasetVersion( + datasetUri, + DatasetType.UriFolder, + isReference, + stage, + id, + name, + version, + description, + tags, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// If PendingUploadId is not provided, a random GUID will be used. + /// Name of Azure blob storage connection to use for generating temporary SAS token. + /// TemporaryBlobReference is the only supported type. + /// A new instance for mocking. + public static PendingUploadRequest PendingUploadRequest(string pendingUploadId = null, string connectionName = null, PendingUploadType pendingUploadType = default) + { + return new PendingUploadRequest(pendingUploadId, connectionName, pendingUploadType, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Container-level read, write, list SAS. + /// ID for this upload request. + /// Version of dataset to be created if user did not specify version when initially creating upload. + /// TemporaryBlobReference is the only supported type. + /// A new instance for mocking. + public static PendingUploadResponse PendingUploadResponse(BlobReferenceForConsumption blobReferenceForConsumption = null, string pendingUploadId = null, string datasetVersion = null, PendingUploadType pendingUploadType = default) + { + return new PendingUploadResponse(blobReferenceForConsumption, pendingUploadId, datasetVersion, pendingUploadType, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Blob URI path for client to upload data. Example: https://blob.windows.core.net/Container/Path. + /// ARM ID of the storage account to use. + /// Credential info to access the storage account. + /// A new instance for mocking. + public static BlobReferenceForConsumption BlobReferenceForConsumption(string blobUri = null, string storageAccountArmId = null, SasCredential credential = null) + { + return new BlobReferenceForConsumption(blobUri, storageAccountArmId, credential, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// SAS uri. + /// Type of credential. + /// A new instance for mocking. + public static SasCredential SasCredential(string sasUri = null, SasCredentialType type = default) + { + return new SasCredential(sasUri, type, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Credential info to access the storage account. + /// A new instance for mocking. + public static AssetCredentialResponse AssetCredentialResponse(BlobReferenceForConsumption blobReferenceForConsumption = null) + { + return new AssetCredentialResponse(blobReferenceForConsumption, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Type of index. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// A new instance for mocking. + public static Index Index(string type = null, string stage = null, string id = null, string name = null, string version = null, string description = null, IDictionary tags = null) + { + tags ??= new Dictionary(); + + return new UnknownIndex( + type == null ? default : new IndexType(type), + stage, + id, + name, + version, + description, + tags, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Name of connection to Azure AI Search. + /// Name of index in Azure AI Search resource to attach. + /// A new instance for mocking. + public static AzureAISearchIndex AzureAISearchIndex(string stage = null, string id = null, string name = null, string version = null, string description = null, IDictionary tags = null, string connectionName = null, string indexName = null) + { + tags ??= new Dictionary(); + + return new AzureAISearchIndex( + IndexType.AzureSearch, + stage, + id, + name, + version, + description, + tags, + serializedAdditionalRawData: null, + connectionName, + indexName); + } + + /// Initializes a new instance of . + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Vector store id of managed index. + /// A new instance for mocking. + public static ManagedAzureAISearchIndex ManagedAzureAISearchIndex(string stage = null, string id = null, string name = null, string version = null, string description = null, IDictionary tags = null, string vectorStoreId = null) + { + tags ??= new Dictionary(); + + return new ManagedAzureAISearchIndex( + IndexType.ManagedAzureSearch, + stage, + id, + name, + version, + description, + tags, + serializedAdditionalRawData: null, + vectorStoreId); + } + + /// Initializes a new instance of . + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Name of connection to CosmosDB. + /// Name of the CosmosDB Database. + /// Name of CosmosDB Container. + /// Embedding model configuration. + /// A new instance for mocking. + public static CosmosDBIndex CosmosDBIndex(string stage = null, string id = null, string name = null, string version = null, string description = null, IDictionary tags = null, string connectionName = null, string databaseName = null, string containerName = null, EmbeddingConfiguration embeddingConfiguration = null) + { + tags ??= new Dictionary(); + + return new CosmosDBIndex( + IndexType.CosmosDB, + stage, + id, + name, + version, + description, + tags, + serializedAdditionalRawData: null, + connectionName, + databaseName, + containerName, + embeddingConfiguration); + } + + /// Initializes a new instance of . + /// The type of the deployment. + /// Name of the deployment. + /// A new instance for mocking. + public static Deployment Deployment(string type = null, string name = null) + { + return new UnknownDeployment(type == null ? default : new DeploymentType(type), name, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Name of the deployment. + /// Publisher-specific name of the deployed model. + /// Publisher-specific version of the deployed model. + /// Name of the deployed model's publisher. + /// Capabilities of deployed model. + /// Sku of the model deployment. + /// Name of the connection the deployment comes from. + /// A new instance for mocking. + public static ModelDeployment ModelDeployment(string name = null, string modelName = null, string modelVersion = null, string modelPublisher = null, IReadOnlyDictionary capabilities = null, Sku sku = null, string connectionName = null) + { + capabilities ??= new Dictionary(); + + return new ModelDeployment( + DeploymentType.ModelDeployment, + name, + serializedAdditionalRawData: null, + modelName, + modelVersion, + modelPublisher, + capabilities, + sku, + connectionName); + } + + /// Initializes a new instance of . + /// Sku capacity. + /// Sku family. + /// Sku name. + /// Sku size. + /// Sku tier. + /// A new instance for mocking. + public static Sku Sku(long capacity = default, string family = null, string name = null, string size = null, string tier = null) + { + return new Sku( + capacity, + family, + name, + size, + tier, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Identifier of the red team. + /// Name of the red-team scan. + /// Number of simulation rounds. + /// List of attack strategies or nested lists of attack strategies. + /// Simulation-only or Simulation + Evaluation. Default false, if true the scan outputs conversation not evaluation result. + /// List of risk categories to generate attack objectives for. + /// Application scenario for the red team operation, to generate scenario specific attacks. + /// Red team's tags. Unlike properties, tags are fully mutable. + /// Red team's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// Status of the red-team. It is set by service and is read-only. + /// A new instance for mocking. + public static RedTeam RedTeam(string id = null, string scanName = null, int numTurns = default, IEnumerable attackStrategies = null, bool simulationOnly = default, IEnumerable riskCategories = null, string applicationScenario = null, IDictionary tags = null, IDictionary properties = null, string status = null) + { + attackStrategies ??= new List(); + riskCategories ??= new List(); + tags ??= new Dictionary(); + properties ??= new Dictionary(); + + return new RedTeam( + id, + scanName, + numTurns, + attackStrategies?.ToList(), + simulationOnly, + riskCategories?.ToList(), + applicationScenario, + tags, + properties, + status, + serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ApiKeyCredentials.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ApiKeyCredentials.Serialization.cs new file mode 100644 index 000000000000..e4250e8bacbb --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ApiKeyCredentials.Serialization.cs @@ -0,0 +1,137 @@ +// 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.Projects.OneDP +{ + public partial class ApiKeyCredentials : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ApiKeyCredentials)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (options.Format != "W" && Optional.IsDefined(ApiKey)) + { + writer.WritePropertyName("apiKey"u8); + writer.WriteStringValue(ApiKey); + } + } + + ApiKeyCredentials 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(ApiKeyCredentials)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeApiKeyCredentials(document.RootElement, options); + } + + internal static ApiKeyCredentials DeserializeApiKeyCredentials(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string apiKey = default; + CredentialType authType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("apiKey"u8)) + { + apiKey = property.Value.GetString(); + continue; + } + if (property.NameEquals("authType"u8)) + { + authType = new CredentialType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ApiKeyCredentials(authType, serializedAdditionalRawData, apiKey); + } + + 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(ApiKeyCredentials)} does not support writing '{options.Format}' format."); + } + } + + ApiKeyCredentials 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeApiKeyCredentials(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ApiKeyCredentials)} 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 ApiKeyCredentials FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeApiKeyCredentials(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/ai/Azure.AI.Projects.OneDP/src/Generated/ApiKeyCredentials.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ApiKeyCredentials.cs new file mode 100644 index 000000000000..b72ad938e4d7 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ApiKeyCredentials.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.Projects.OneDP +{ + /// API Key Credential definition. + public partial class ApiKeyCredentials : BaseCredentials + { + /// Initializes a new instance of . + internal ApiKeyCredentials() + { + AuthType = CredentialType.ApiKey; + } + + /// Initializes a new instance of . + /// The type of credential used by the connection. + /// Keeps track of any properties unknown to the library. + /// API Key. + internal ApiKeyCredentials(CredentialType authType, IDictionary serializedAdditionalRawData, string apiKey) : base(authType, serializedAdditionalRawData) + { + ApiKey = apiKey; + } + + /// API Key. + public string ApiKey { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AssetCredentialResponse.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AssetCredentialResponse.Serialization.cs new file mode 100644 index 000000000000..5cbfc0bdfa5b --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AssetCredentialResponse.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.Projects.OneDP +{ + public partial class AssetCredentialResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssetCredentialResponse)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("blobReferenceForConsumption"u8); + writer.WriteObjectValue(BlobReferenceForConsumption, 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AssetCredentialResponse 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(AssetCredentialResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAssetCredentialResponse(document.RootElement, options); + } + + internal static AssetCredentialResponse DeserializeAssetCredentialResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BlobReferenceForConsumption blobReferenceForConsumption = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("blobReferenceForConsumption"u8)) + { + blobReferenceForConsumption = BlobReferenceForConsumption.DeserializeBlobReferenceForConsumption(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AssetCredentialResponse(blobReferenceForConsumption, 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(AssetCredentialResponse)} does not support writing '{options.Format}' format."); + } + } + + AssetCredentialResponse 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssetCredentialResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssetCredentialResponse)} 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 AssetCredentialResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssetCredentialResponse(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/ai/Azure.AI.Projects.OneDP/src/Generated/AssetCredentialResponse.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AssetCredentialResponse.cs new file mode 100644 index 000000000000..5a0abe5ddc4b --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AssetCredentialResponse.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.Projects.OneDP +{ + /// Represents a reference to a blob for consumption. + public partial class AssetCredentialResponse + { + /// + /// 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 . + /// Credential info to access the storage account. + /// is null. + internal AssetCredentialResponse(BlobReferenceForConsumption blobReferenceForConsumption) + { + Argument.AssertNotNull(blobReferenceForConsumption, nameof(blobReferenceForConsumption)); + + BlobReferenceForConsumption = blobReferenceForConsumption; + } + + /// Initializes a new instance of . + /// Credential info to access the storage account. + /// Keeps track of any properties unknown to the library. + internal AssetCredentialResponse(BlobReferenceForConsumption blobReferenceForConsumption, IDictionary serializedAdditionalRawData) + { + BlobReferenceForConsumption = blobReferenceForConsumption; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AssetCredentialResponse() + { + } + + /// Credential info to access the storage account. + public BlobReferenceForConsumption BlobReferenceForConsumption { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AttackStrategy.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AttackStrategy.cs new file mode 100644 index 000000000000..8c8072533d45 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AttackStrategy.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.Projects.OneDP +{ + /// Strategies for attacks. + public readonly partial struct AttackStrategy : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AttackStrategy(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EasyValue = "easy"; + private const string ModerateValue = "moderate"; + private const string DifficultValue = "difficult"; + private const string AsciiArtValue = "ascii_art"; + private const string AsciiSmugglerValue = "ascii_smuggler"; + private const string AtbashValue = "atbash"; + private const string Base64Value = "base64"; + private const string BinaryValue = "binary"; + private const string CaesarValue = "caesar"; + private const string CharacterSpaceValue = "character_space"; + private const string JailbreakValue = "jailbreak"; + private const string AnsiiAttackValue = "ansii_attack"; + private const string CharacterSwapValue = "character_swap"; + private const string SuffixAppendValue = "suffix_append"; + private const string StringJoinValue = "string_join"; + private const string UnicodeConfusableValue = "unicode_confusable"; + private const string UnicodeSubstitutionValue = "unicode_substitution"; + private const string DiacriticValue = "diacritic"; + private const string FlipValue = "flip"; + private const string LeetspeakValue = "leetspeak"; + private const string ROT13Value = "rot13"; + private const string MorseValue = "morse"; + private const string UrlValue = "url"; + private const string BaselineValue = "baseline"; + + /// Represents a default set of easy complexity attacks. Easy complexity attacks require less effort, such as translation of a prompt into some encoding, and does not require any Large Language Model to convert or orchestrate. + public static AttackStrategy Easy { get; } = new AttackStrategy(EasyValue); + /// Represents a default set of moderate complexity attacks. Moderate complexity attacks require having access to resources such as another generative AI model. + public static AttackStrategy Moderate { get; } = new AttackStrategy(ModerateValue); + /// Represents a default set of difficult complexity attacks. Difficult complexity attacks include attacks that require access to significant resources and effort to execute an attack such as knowledge of search-based algorithms in addition to a generative AI model. + public static AttackStrategy Difficult { get; } = new AttackStrategy(DifficultValue); + /// Generates visual art using ASCII characters, often used for creative or obfuscation purposes. + public static AttackStrategy AsciiArt { get; } = new AttackStrategy(AsciiArtValue); + /// Conceals data within ASCII characters, making it harder to detect. + public static AttackStrategy AsciiSmuggler { get; } = new AttackStrategy(AsciiSmugglerValue); + /// Implements the Atbash cipher, a simple substitution cipher where each letter is mapped to its reverse. + public static AttackStrategy Atbash { get; } = new AttackStrategy(AtbashValue); + /// Encodes binary data into a text format using Base64, commonly used for data transmission. + public static AttackStrategy Base64 { get; } = new AttackStrategy(Base64Value); + /// Converts text into binary code, representing data in a series of 0s and 1s. + public static AttackStrategy Binary { get; } = new AttackStrategy(BinaryValue); + /// Applies the Caesar cipher, a substitution cipher that shifts characters by a fixed number of positions. + public static AttackStrategy Caesar { get; } = new AttackStrategy(CaesarValue); + /// Alters text by adding spaces between characters, often used for obfuscation. + public static AttackStrategy CharacterSpace { get; } = new AttackStrategy(CharacterSpaceValue); + /// Injects specially crafted prompts to bypass AI safeguards, known as User Injected Prompt Attacks (UPIA). + public static AttackStrategy Jailbreak { get; } = new AttackStrategy(JailbreakValue); + /// Utilizes ANSI escape sequences to manipulate text appearance and behavior. + public static AttackStrategy AnsiiAttack { get; } = new AttackStrategy(AnsiiAttackValue); + /// Swaps characters within text to create variations or obfuscate the original content. + public static AttackStrategy CharacterSwap { get; } = new AttackStrategy(CharacterSwapValue); + /// Appends an adversarial suffix to the prompt. + public static AttackStrategy SuffixAppend { get; } = new AttackStrategy(SuffixAppendValue); + /// Joins multiple strings together, often used for concatenation or obfuscation. + public static AttackStrategy StringJoin { get; } = new AttackStrategy(StringJoinValue); + /// Uses Unicode characters that look similar to standard characters, creating visual confusion. + public static AttackStrategy UnicodeConfusable { get; } = new AttackStrategy(UnicodeConfusableValue); + /// Substitutes standard characters with Unicode equivalents, often for obfuscation. + public static AttackStrategy UnicodeSubstitution { get; } = new AttackStrategy(UnicodeSubstitutionValue); + /// Adds diacritical marks to characters, changing their appearance and sometimes their meaning. + public static AttackStrategy Diacritic { get; } = new AttackStrategy(DiacriticValue); + /// Flips characters from front to back, creating a mirrored effect. + public static AttackStrategy Flip { get; } = new AttackStrategy(FlipValue); + /// Transforms text into Leetspeak, a form of encoding that replaces letters with similar-looking numbers or symbols. + public static AttackStrategy Leetspeak { get; } = new AttackStrategy(LeetspeakValue); + /// Applies the ROT13 cipher, a simple substitution cipher that shifts characters by 13 positions. + public static AttackStrategy ROT13 { get; } = new AttackStrategy(ROT13Value); + /// Encodes text into Morse code, using dots and dashes to represent characters. + public static AttackStrategy Morse { get; } = new AttackStrategy(MorseValue); + /// Encodes text into URL format. + public static AttackStrategy Url { get; } = new AttackStrategy(UrlValue); + /// Represents the baseline direct adversarial probing, which is used by attack strategies as the attack objective. + public static AttackStrategy Baseline { get; } = new AttackStrategy(BaselineValue); + /// Determines if two values are the same. + public static bool operator ==(AttackStrategy left, AttackStrategy right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AttackStrategy left, AttackStrategy right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AttackStrategy(string value) => new AttackStrategy(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AttackStrategy other && Equals(other); + /// + public bool Equals(AttackStrategy 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/ai/Azure.AI.Projects.OneDP/src/Generated/AzureAISearchIndex.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AzureAISearchIndex.Serialization.cs new file mode 100644 index 000000000000..32b697535785 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AzureAISearchIndex.Serialization.cs @@ -0,0 +1,197 @@ +// 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.Projects.OneDP +{ + public partial class AzureAISearchIndex : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureAISearchIndex)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("connectionName"u8); + writer.WriteStringValue(ConnectionName); + writer.WritePropertyName("indexName"u8); + writer.WriteStringValue(IndexName); + } + + AzureAISearchIndex 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(AzureAISearchIndex)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureAISearchIndex(document.RootElement, options); + } + + internal static AzureAISearchIndex DeserializeAzureAISearchIndex(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string connectionName = default; + string indexName = default; + IndexType type = default; + string stage = default; + string id = default; + string name = default; + string version = default; + string description = default; + IDictionary tags = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("connectionName"u8)) + { + connectionName = property.Value.GetString(); + continue; + } + if (property.NameEquals("indexName"u8)) + { + indexName = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new IndexType(property.Value.GetString()); + continue; + } + if (property.NameEquals("stage"u8)) + { + stage = property.Value.GetString(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("version"u8)) + { + version = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("tags"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()); + } + tags = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureAISearchIndex( + type, + stage, + id, + name, + version, + description, + tags ?? new ChangeTrackingDictionary(), + serializedAdditionalRawData, + connectionName, + indexName); + } + + 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(AzureAISearchIndex)} does not support writing '{options.Format}' format."); + } + } + + AzureAISearchIndex 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureAISearchIndex(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureAISearchIndex)} 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 AzureAISearchIndex FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureAISearchIndex(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/ai/Azure.AI.Projects.OneDP/src/Generated/AzureAISearchIndex.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AzureAISearchIndex.cs new file mode 100644 index 000000000000..f386432d38b9 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/AzureAISearchIndex.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + /// Azure AI Search Index Definition. + public partial class AzureAISearchIndex : Index + { + /// Initializes a new instance of . + /// Name of connection to Azure AI Search. + /// Name of index in Azure AI Search resource to attach. + /// or is null. + public AzureAISearchIndex(string connectionName, string indexName) + { + Argument.AssertNotNull(connectionName, nameof(connectionName)); + Argument.AssertNotNull(indexName, nameof(indexName)); + + Type = IndexType.AzureSearch; + ConnectionName = connectionName; + IndexName = indexName; + } + + /// Initializes a new instance of . + /// Type of index. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Keeps track of any properties unknown to the library. + /// Name of connection to Azure AI Search. + /// Name of index in Azure AI Search resource to attach. + internal AzureAISearchIndex(IndexType type, string stage, string id, string name, string version, string description, IDictionary tags, IDictionary serializedAdditionalRawData, string connectionName, string indexName) : base(type, stage, id, name, version, description, tags, serializedAdditionalRawData) + { + ConnectionName = connectionName; + IndexName = indexName; + } + + /// Initializes a new instance of for deserialization. + internal AzureAISearchIndex() + { + } + + /// Name of connection to Azure AI Search. + public string ConnectionName { get; set; } + /// Name of index in Azure AI Search resource to attach. + public string IndexName { get; set; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/BaseCredentials.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/BaseCredentials.Serialization.cs new file mode 100644 index 000000000000..4e302bf54def --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/BaseCredentials.Serialization.cs @@ -0,0 +1,137 @@ +// 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.Projects.OneDP +{ + [PersistableModelProxy(typeof(UnknownBaseCredentials))] + public partial class BaseCredentials : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BaseCredentials)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("authType"u8); + writer.WriteStringValue(AuthType.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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + BaseCredentials 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(BaseCredentials)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBaseCredentials(document.RootElement, options); + } + + internal static BaseCredentials DeserializeBaseCredentials(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("authType", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "AAD": return EntraIDCredentials.DeserializeEntraIDCredentials(element, options); + case "ApiKey": return ApiKeyCredentials.DeserializeApiKeyCredentials(element, options); + case "CustomKeys": return CustomCredential.DeserializeCustomCredential(element, options); + case "None": return NoAuthenticationCredentials.DeserializeNoAuthenticationCredentials(element, options); + case "SAS": return SASCredentials.DeserializeSASCredentials(element, options); + } + } + return UnknownBaseCredentials.DeserializeUnknownBaseCredentials(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(BaseCredentials)} does not support writing '{options.Format}' format."); + } + } + + BaseCredentials 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBaseCredentials(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BaseCredentials)} 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 BaseCredentials FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBaseCredentials(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/ai/Azure.AI.Projects.OneDP/src/Generated/BaseCredentials.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/BaseCredentials.cs new file mode 100644 index 000000000000..49e30bc72ce0 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/BaseCredentials.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.Projects.OneDP +{ + /// + /// A base class for connection credentials + /// 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 BaseCredentials + { + /// + /// 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 BaseCredentials() + { + } + + /// Initializes a new instance of . + /// The type of credential used by the connection. + /// Keeps track of any properties unknown to the library. + internal BaseCredentials(CredentialType authType, IDictionary serializedAdditionalRawData) + { + AuthType = authType; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The type of credential used by the connection. + internal CredentialType AuthType { get; set; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/BlobReferenceForConsumption.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/BlobReferenceForConsumption.Serialization.cs new file mode 100644 index 000000000000..eedd81b445eb --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/BlobReferenceForConsumption.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.Projects.OneDP +{ + public partial class BlobReferenceForConsumption : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BlobReferenceForConsumption)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("blobUri"u8); + writer.WriteStringValue(BlobUri); + writer.WritePropertyName("storageAccountArmId"u8); + writer.WriteStringValue(StorageAccountArmId); + writer.WritePropertyName("credential"u8); + writer.WriteObjectValue(Credential, 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + BlobReferenceForConsumption 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(BlobReferenceForConsumption)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBlobReferenceForConsumption(document.RootElement, options); + } + + internal static BlobReferenceForConsumption DeserializeBlobReferenceForConsumption(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string blobUri = default; + string storageAccountArmId = default; + SasCredential credential = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("blobUri"u8)) + { + blobUri = property.Value.GetString(); + continue; + } + if (property.NameEquals("storageAccountArmId"u8)) + { + storageAccountArmId = property.Value.GetString(); + continue; + } + if (property.NameEquals("credential"u8)) + { + credential = SasCredential.DeserializeSasCredential(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BlobReferenceForConsumption(blobUri, storageAccountArmId, credential, 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(BlobReferenceForConsumption)} does not support writing '{options.Format}' format."); + } + } + + BlobReferenceForConsumption 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBlobReferenceForConsumption(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BlobReferenceForConsumption)} 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 BlobReferenceForConsumption FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBlobReferenceForConsumption(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/ai/Azure.AI.Projects.OneDP/src/Generated/BlobReferenceForConsumption.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/BlobReferenceForConsumption.cs new file mode 100644 index 000000000000..92c798d2b25a --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/BlobReferenceForConsumption.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.Projects.OneDP +{ + /// Represents a reference to a blob for consumption. + public partial class BlobReferenceForConsumption + { + /// + /// 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 . + /// Blob URI path for client to upload data. Example: https://blob.windows.core.net/Container/Path. + /// ARM ID of the storage account to use. + /// Credential info to access the storage account. + /// , or is null. + internal BlobReferenceForConsumption(string blobUri, string storageAccountArmId, SasCredential credential) + { + Argument.AssertNotNull(blobUri, nameof(blobUri)); + Argument.AssertNotNull(storageAccountArmId, nameof(storageAccountArmId)); + Argument.AssertNotNull(credential, nameof(credential)); + + BlobUri = blobUri; + StorageAccountArmId = storageAccountArmId; + Credential = credential; + } + + /// Initializes a new instance of . + /// Blob URI path for client to upload data. Example: https://blob.windows.core.net/Container/Path. + /// ARM ID of the storage account to use. + /// Credential info to access the storage account. + /// Keeps track of any properties unknown to the library. + internal BlobReferenceForConsumption(string blobUri, string storageAccountArmId, SasCredential credential, IDictionary serializedAdditionalRawData) + { + BlobUri = blobUri; + StorageAccountArmId = storageAccountArmId; + Credential = credential; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal BlobReferenceForConsumption() + { + } + + /// Blob URI path for client to upload data. Example: https://blob.windows.core.net/Container/Path. + public string BlobUri { get; } + /// ARM ID of the storage account to use. + public string StorageAccountArmId { get; } + /// Credential info to access the storage account. + public SasCredential Credential { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Connection.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Connection.Serialization.cs new file mode 100644 index 000000000000..3cd9ef6f108f --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Connection.Serialization.cs @@ -0,0 +1,162 @@ +// 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.Projects.OneDP +{ + [PersistableModelProxy(typeof(UnknownConnection))] + public partial class Connection : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Connection)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("authType"u8); + writer.WriteStringValue(AuthType); + if (options.Format != "W") + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (options.Format != "W") + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + } + if (options.Format != "W") + { + writer.WritePropertyName("target"u8); + writer.WriteStringValue(Target); + } + if (options.Format != "W") + { + writer.WritePropertyName("isDefault"u8); + writer.WriteBooleanValue(IsDefault); + } + if (options.Format != "W") + { + writer.WritePropertyName("credentials"u8); + writer.WriteObjectValue(Credentials, options); + } + if (options.Format != "W") + { + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Connection 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(Connection)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeConnection(document.RootElement, options); + } + + internal static Connection DeserializeConnection(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + return UnknownConnection.DeserializeUnknownConnection(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(Connection)} does not support writing '{options.Format}' format."); + } + } + + Connection 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeConnection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Connection)} 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 Connection FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeConnection(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/ai/Azure.AI.Projects.OneDP/src/Generated/Connection.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Connection.cs new file mode 100644 index 000000000000..7b117e3e30ea --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Connection.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.Projects.OneDP +{ + /// Response from the list and get connections operations. + public abstract partial class Connection + { + /// + /// 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 Connection() + { + Metadata = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// Discriminator property for Connection. + /// The name of the resource. + /// Category of the connection. + /// The connection URL to be used for this service. + /// Whether the connection is tagged as the default connection of its type. + /// + /// The credentials used by the connection + /// 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 . + /// + /// Metadata of the connection. + /// Keeps track of any properties unknown to the library. + internal Connection(string authType, string name, ConnectionType type, string target, bool isDefault, BaseCredentials credentials, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + { + AuthType = authType; + Name = name; + Type = type; + Target = target; + IsDefault = isDefault; + Credentials = credentials; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Discriminator property for Connection. + internal string AuthType { get; set; } + /// The name of the resource. + public string Name { get; } + /// Category of the connection. + public ConnectionType Type { get; } + /// The connection URL to be used for this service. + public string Target { get; } + /// Whether the connection is tagged as the default connection of its type. + public bool IsDefault { get; } + /// + /// The credentials used by the connection + /// 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 BaseCredentials Credentials { get; } + /// Metadata of the connection. + public IReadOnlyDictionary Metadata { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ConnectionType.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ConnectionType.cs new file mode 100644 index 000000000000..375362702d4a --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ConnectionType.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.Projects.OneDP +{ + /// The Type (or category) of the connection. + public readonly partial struct ConnectionType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ConnectionType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AzureOpenAIValue = "AzureOpenAI"; + private const string AzureBlobStorageValue = "AzureBlob"; + private const string AzureStorageAccountValue = "AzureStorageAccount"; + private const string AzureAISearchValue = "CognitiveSearch"; + private const string CosmosDBValue = "CosmosDB"; + private const string APIKeyValue = "ApiKey"; + private const string ApplicationConfigurationValue = "AppConfig"; + private const string ApplicationInsightsValue = "AppInsights"; + private const string CustomValue = "CustomKeys"; + + /// Azure OpenAI Service. + public static ConnectionType AzureOpenAI { get; } = new ConnectionType(AzureOpenAIValue); + /// Azure Blob Storage, with specified container. + public static ConnectionType AzureBlobStorage { get; } = new ConnectionType(AzureBlobStorageValue); + /// Azure Blob Storage, with container not specified (used by Assistants). + public static ConnectionType AzureStorageAccount { get; } = new ConnectionType(AzureStorageAccountValue); + /// Azure AI Search. + public static ConnectionType AzureAISearch { get; } = new ConnectionType(AzureAISearchValue); + /// CosmosDB. + public static ConnectionType CosmosDB { get; } = new ConnectionType(CosmosDBValue); + /// Generic connection that uses API Key authentication. + public static ConnectionType APIKey { get; } = new ConnectionType(APIKeyValue); + /// Application Configuration. + public static ConnectionType ApplicationConfiguration { get; } = new ConnectionType(ApplicationConfigurationValue); + /// Application Insights. + public static ConnectionType ApplicationInsights { get; } = new ConnectionType(ApplicationInsightsValue); + /// Custom Keys. + public static ConnectionType Custom { get; } = new ConnectionType(CustomValue); + /// Determines if two values are the same. + public static bool operator ==(ConnectionType left, ConnectionType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ConnectionType left, ConnectionType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ConnectionType(string value) => new ConnectionType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ConnectionType other && Equals(other); + /// + public bool Equals(ConnectionType 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/ai/Azure.AI.Projects.OneDP/src/Generated/Connections.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Connections.cs new file mode 100644 index 000000000000..83c023b071d7 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Connections.cs @@ -0,0 +1,594 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.Projects.OneDP +{ + // Data plane generated sub-client. + /// The Connections sub-client. + public partial class Connections + { + private const string AuthorizationHeader = "Authorization"; + private readonly AzureKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + 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 Connections for mocking. + protected Connections() + { + } + + /// Initializes a new instance of Connections. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The key credential to copy. + /// The token credential to copy. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// The API version to use for this operation. + internal Connections(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _keyCredential = keyCredential; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Get a connection by name, without populating connection credentials. + /// The name of the resource. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetConnectionAsync(string name, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetConnectionAsync(name, context).ConfigureAwait(false); + return Response.FromValue(Connection.FromResponse(response), response); + } + + /// Get a connection by name, without populating connection credentials. + /// The name of the resource. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetConnection(string name, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetConnection(name, context); + return Response.FromValue(Connection.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get a connection by name, without populating connection credentials + /// + /// + /// + /// 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 name of the resource. + /// 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. + public virtual async Task GetConnectionAsync(string name, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + using var scope = ClientDiagnostics.CreateScope("Connections.GetConnection"); + scope.Start(); + try + { + using HttpMessage message = CreateGetConnectionRequest(name, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get a connection by name, without populating connection credentials + /// + /// + /// + /// 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 name of the resource. + /// 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. + public virtual Response GetConnection(string name, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + using var scope = ClientDiagnostics.CreateScope("Connections.GetConnection"); + scope.Start(); + try + { + using HttpMessage message = CreateGetConnectionRequest(name, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Get a connection by name, with its connection credentials. + /// The name of the resource. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetWithCredentialsAsync(string name, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetWithCredentialsAsync(name, context).ConfigureAwait(false); + return Response.FromValue(Connection.FromResponse(response), response); + } + + /// Get a connection by name, with its connection credentials. + /// The name of the resource. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetWithCredentials(string name, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetWithCredentials(name, context); + return Response.FromValue(Connection.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get a connection by name, with its connection credentials + /// + /// + /// + /// 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 name of the resource. + /// 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. + public virtual async Task GetWithCredentialsAsync(string name, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + using var scope = ClientDiagnostics.CreateScope("Connections.GetWithCredentials"); + scope.Start(); + try + { + using HttpMessage message = CreateGetWithCredentialsRequest(name, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get a connection by name, with its connection credentials + /// + /// + /// + /// 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 name of the resource. + /// 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. + public virtual Response GetWithCredentials(string name, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + using var scope = ClientDiagnostics.CreateScope("Connections.GetWithCredentials"); + scope.Start(); + try + { + using HttpMessage message = CreateGetWithCredentialsRequest(name, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// List all connections in the project, without populating connection credentials. + /// List connections of this specific type. + /// List connections that are default connections. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + public virtual AsyncPageable GetConnectionsAsync(ConnectionType? connectionType = null, bool? defaultConnection = null, int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetConnectionsRequest(connectionType?.ToString(), defaultConnection, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetConnectionsNextPageRequest(nextLink, connectionType?.ToString(), defaultConnection, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => Connection.DeserializeConnection(e), ClientDiagnostics, _pipeline, "Connections.GetConnections", "value", "nextLink", maxpagesize, context); + } + + /// List all connections in the project, without populating connection credentials. + /// List connections of this specific type. + /// List connections that are default connections. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + public virtual Pageable GetConnections(ConnectionType? connectionType = null, bool? defaultConnection = null, int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetConnectionsRequest(connectionType?.ToString(), defaultConnection, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetConnectionsNextPageRequest(nextLink, connectionType?.ToString(), defaultConnection, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => Connection.DeserializeConnection(e), ClientDiagnostics, _pipeline, "Connections.GetConnections", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List all connections in the project, without populating connection credentials + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// List connections of this specific type. Allowed values: "AzureOpenAI" | "AzureBlob" | "AzureStorageAccount" | "CognitiveSearch" | "CosmosDB" | "ApiKey" | "AppConfig" | "AppInsights" | "CustomKeys". + /// List connections that are default connections. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual AsyncPageable GetConnectionsAsync(string connectionType, bool? defaultConnection, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetConnectionsRequest(connectionType, defaultConnection, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetConnectionsNextPageRequest(nextLink, connectionType, defaultConnection, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Connections.GetConnections", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List all connections in the project, without populating connection credentials + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// List connections of this specific type. Allowed values: "AzureOpenAI" | "AzureBlob" | "AzureStorageAccount" | "CognitiveSearch" | "CosmosDB" | "ApiKey" | "AppConfig" | "AppInsights" | "CustomKeys". + /// List connections that are default connections. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual Pageable GetConnections(string connectionType, bool? defaultConnection, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetConnectionsRequest(connectionType, defaultConnection, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetConnectionsNextPageRequest(nextLink, connectionType, defaultConnection, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Connections.GetConnections", "value", "nextLink", maxpagesize, context); + } + + /// List all connections in the project, with their connection credentials. + /// List connections of this specific type. + /// List connections that are default connections. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + public virtual AsyncPageable GetWithCredentialsAsync(ConnectionType? connectionType = null, bool? defaultConnection = null, int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetWithCredentialsRequest(connectionType?.ToString(), defaultConnection, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetWithCredentialsNextPageRequest(nextLink, connectionType?.ToString(), defaultConnection, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => Connection.DeserializeConnection(e), ClientDiagnostics, _pipeline, "Connections.GetWithCredentials", "value", "nextLink", maxpagesize, context); + } + + /// List all connections in the project, with their connection credentials. + /// List connections of this specific type. + /// List connections that are default connections. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + public virtual Pageable GetWithCredentials(ConnectionType? connectionType = null, bool? defaultConnection = null, int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetWithCredentialsRequest(connectionType?.ToString(), defaultConnection, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetWithCredentialsNextPageRequest(nextLink, connectionType?.ToString(), defaultConnection, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => Connection.DeserializeConnection(e), ClientDiagnostics, _pipeline, "Connections.GetWithCredentials", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List all connections in the project, with their connection credentials + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// List connections of this specific type. Allowed values: "AzureOpenAI" | "AzureBlob" | "AzureStorageAccount" | "CognitiveSearch" | "CosmosDB" | "ApiKey" | "AppConfig" | "AppInsights" | "CustomKeys". + /// List connections that are default connections. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual AsyncPageable GetWithCredentialsAsync(string connectionType, bool? defaultConnection, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetWithCredentialsRequest(connectionType, defaultConnection, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetWithCredentialsNextPageRequest(nextLink, connectionType, defaultConnection, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Connections.GetWithCredentials", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List all connections in the project, with their connection credentials + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// List connections of this specific type. Allowed values: "AzureOpenAI" | "AzureBlob" | "AzureStorageAccount" | "CognitiveSearch" | "CosmosDB" | "ApiKey" | "AppConfig" | "AppInsights" | "CustomKeys". + /// List connections that are default connections. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual Pageable GetWithCredentials(string connectionType, bool? defaultConnection, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetWithCredentialsRequest(connectionType, defaultConnection, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetWithCredentialsNextPageRequest(nextLink, connectionType, defaultConnection, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Connections.GetWithCredentials", "value", "nextLink", maxpagesize, context); + } + + internal HttpMessage CreateGetConnectionRequest(string name, 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("/connections/", false); + uri.AppendPath(name, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetWithCredentialsRequest(string name, 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("/connections/", false); + uri.AppendPath(name, true); + uri.AppendPath("/withCredentials", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetConnectionsRequest(string connectionType, bool? defaultConnection, int? maxCount, int? skip, int? maxpagesize, 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("/connections", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (connectionType != null) + { + uri.AppendQuery("connectionType", connectionType, true); + } + if (defaultConnection != null) + { + uri.AppendQuery("defaultConnection", defaultConnection.Value, true); + } + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetWithCredentialsRequest(string connectionType, bool? defaultConnection, int? maxCount, int? skip, int? maxpagesize, 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("/connections/withCredentials", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (connectionType != null) + { + uri.AppendQuery("connectionType", connectionType, true); + } + if (defaultConnection != null) + { + uri.AppendQuery("defaultConnection", defaultConnection.Value, true); + } + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetConnectionsNextPageRequest(string nextLink, string connectionType, bool? defaultConnection, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetWithCredentialsNextPageRequest(string nextLink, string connectionType, bool? defaultConnection, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, 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 }); + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CosmosDBIndex.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CosmosDBIndex.Serialization.cs new file mode 100644 index 000000000000..d1e12fc4bb57 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CosmosDBIndex.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.Projects.OneDP +{ + public partial class CosmosDBIndex : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CosmosDBIndex)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("connectionName"u8); + writer.WriteStringValue(ConnectionName); + writer.WritePropertyName("databaseName"u8); + writer.WriteStringValue(DatabaseName); + writer.WritePropertyName("containerName"u8); + writer.WriteStringValue(ContainerName); + writer.WritePropertyName("embeddingConfiguration"u8); + writer.WriteObjectValue(EmbeddingConfiguration, options); + } + + CosmosDBIndex 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(CosmosDBIndex)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCosmosDBIndex(document.RootElement, options); + } + + internal static CosmosDBIndex DeserializeCosmosDBIndex(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string connectionName = default; + string databaseName = default; + string containerName = default; + EmbeddingConfiguration embeddingConfiguration = default; + IndexType type = default; + string stage = default; + string id = default; + string name = default; + string version = default; + string description = default; + IDictionary tags = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("connectionName"u8)) + { + connectionName = property.Value.GetString(); + continue; + } + if (property.NameEquals("databaseName"u8)) + { + databaseName = property.Value.GetString(); + continue; + } + if (property.NameEquals("containerName"u8)) + { + containerName = property.Value.GetString(); + continue; + } + if (property.NameEquals("embeddingConfiguration"u8)) + { + embeddingConfiguration = EmbeddingConfiguration.DeserializeEmbeddingConfiguration(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new IndexType(property.Value.GetString()); + continue; + } + if (property.NameEquals("stage"u8)) + { + stage = property.Value.GetString(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("version"u8)) + { + version = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("tags"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()); + } + tags = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CosmosDBIndex( + type, + stage, + id, + name, + version, + description, + tags ?? new ChangeTrackingDictionary(), + serializedAdditionalRawData, + connectionName, + databaseName, + containerName, + embeddingConfiguration); + } + + 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(CosmosDBIndex)} does not support writing '{options.Format}' format."); + } + } + + CosmosDBIndex 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCosmosDBIndex(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CosmosDBIndex)} 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 CosmosDBIndex FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCosmosDBIndex(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/ai/Azure.AI.Projects.OneDP/src/Generated/CosmosDBIndex.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CosmosDBIndex.cs new file mode 100644 index 000000000000..85649157ac70 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CosmosDBIndex.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.Projects.OneDP +{ + /// CosmosDB Vector Store Index Definition. + public partial class CosmosDBIndex : Index + { + /// Initializes a new instance of . + /// Name of connection to CosmosDB. + /// Name of the CosmosDB Database. + /// Name of CosmosDB Container. + /// Embedding model configuration. + /// , , or is null. + public CosmosDBIndex(string connectionName, string databaseName, string containerName, EmbeddingConfiguration embeddingConfiguration) + { + Argument.AssertNotNull(connectionName, nameof(connectionName)); + Argument.AssertNotNull(databaseName, nameof(databaseName)); + Argument.AssertNotNull(containerName, nameof(containerName)); + Argument.AssertNotNull(embeddingConfiguration, nameof(embeddingConfiguration)); + + Type = IndexType.CosmosDB; + ConnectionName = connectionName; + DatabaseName = databaseName; + ContainerName = containerName; + EmbeddingConfiguration = embeddingConfiguration; + } + + /// Initializes a new instance of . + /// Type of index. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Keeps track of any properties unknown to the library. + /// Name of connection to CosmosDB. + /// Name of the CosmosDB Database. + /// Name of CosmosDB Container. + /// Embedding model configuration. + internal CosmosDBIndex(IndexType type, string stage, string id, string name, string version, string description, IDictionary tags, IDictionary serializedAdditionalRawData, string connectionName, string databaseName, string containerName, EmbeddingConfiguration embeddingConfiguration) : base(type, stage, id, name, version, description, tags, serializedAdditionalRawData) + { + ConnectionName = connectionName; + DatabaseName = databaseName; + ContainerName = containerName; + EmbeddingConfiguration = embeddingConfiguration; + } + + /// Initializes a new instance of for deserialization. + internal CosmosDBIndex() + { + } + + /// Name of connection to CosmosDB. + public string ConnectionName { get; set; } + /// Name of the CosmosDB Database. + public string DatabaseName { get; set; } + /// Name of CosmosDB Container. + public string ContainerName { get; set; } + /// Embedding model configuration. + public EmbeddingConfiguration EmbeddingConfiguration { get; set; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CredentialType.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CredentialType.cs new file mode 100644 index 000000000000..514a83343de4 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CredentialType.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.Projects.OneDP +{ + /// The credential type used by the connection. + internal readonly partial struct CredentialType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public CredentialType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ApiKeyValue = "ApiKey"; + private const string EntraIdValue = "AAD"; + private const string SASValue = "SAS"; + private const string CustomValue = "CustomKeys"; + private const string NoneValue = "None"; + + /// API Key credential. + public static CredentialType ApiKey { get; } = new CredentialType(ApiKeyValue); + /// Entra ID credential (formerly known as AAD). + public static CredentialType EntraId { get; } = new CredentialType(EntraIdValue); + /// Shared Access Signature (SAS) credential. + public static CredentialType SAS { get; } = new CredentialType(SASValue); + /// Custom credential. + public static CredentialType Custom { get; } = new CredentialType(CustomValue); + /// No credential. + public static CredentialType None { get; } = new CredentialType(NoneValue); + /// Determines if two values are the same. + public static bool operator ==(CredentialType left, CredentialType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(CredentialType left, CredentialType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator CredentialType(string value) => new CredentialType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is CredentialType other && Equals(other); + /// + public bool Equals(CredentialType 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/ai/Azure.AI.Projects.OneDP/src/Generated/CustomCredential.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CustomCredential.Serialization.cs new file mode 100644 index 000000000000..bf480262d9a1 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CustomCredential.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.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + public partial class CustomCredential : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CustomCredential)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + CustomCredential 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(CustomCredential)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCustomCredential(document.RootElement, options); + } + + internal static CustomCredential DeserializeCustomCredential(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CredentialType authType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("authType"u8)) + { + authType = new CredentialType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CustomCredential(authType, 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(CustomCredential)} does not support writing '{options.Format}' format."); + } + } + + CustomCredential 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCustomCredential(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CustomCredential)} 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 CustomCredential FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCustomCredential(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/ai/Azure.AI.Projects.OneDP/src/Generated/CustomCredential.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CustomCredential.cs new file mode 100644 index 000000000000..c2348eac4371 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/CustomCredential.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.Projects.OneDP +{ + /// Custom credential defintion. + public partial class CustomCredential : BaseCredentials + { + /// Initializes a new instance of . + internal CustomCredential() + { + AuthType = CredentialType.Custom; + } + + /// Initializes a new instance of . + /// The type of credential used by the connection. + /// Keeps track of any properties unknown to the library. + internal CustomCredential(CredentialType authType, IDictionary serializedAdditionalRawData) : base(authType, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/DatasetType.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/DatasetType.cs new file mode 100644 index 000000000000..4be625d96a85 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/DatasetType.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.Projects.OneDP +{ + /// Enum to determine the type of data. + internal readonly partial struct DatasetType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DatasetType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UriFileValue = "uri_file"; + private const string UriFolderValue = "uri_folder"; + + /// URI file. + public static DatasetType UriFile { get; } = new DatasetType(UriFileValue); + /// URI folder. + public static DatasetType UriFolder { get; } = new DatasetType(UriFolderValue); + /// Determines if two values are the same. + public static bool operator ==(DatasetType left, DatasetType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DatasetType left, DatasetType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DatasetType(string value) => new DatasetType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DatasetType other && Equals(other); + /// + public bool Equals(DatasetType 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/ai/Azure.AI.Projects.OneDP/src/Generated/DatasetVersion.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/DatasetVersion.Serialization.cs new file mode 100644 index 000000000000..16279d2cddce --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/DatasetVersion.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.Text.Json; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + [PersistableModelProxy(typeof(UnknownDatasetVersion))] + public partial class DatasetVersion : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DatasetVersion)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("datasetUri"u8); + writer.WriteStringValue(DatasetUri); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && Optional.IsDefined(IsReference)) + { + writer.WritePropertyName("isReference"u8); + writer.WriteBooleanValue(IsReference.Value); + } + if (Optional.IsDefined(Stage)) + { + writer.WritePropertyName("stage"u8); + writer.WriteStringValue(Stage); + } + if (options.Format != "W" && Optional.IsDefined(Id)) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (options.Format != "W") + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (options.Format != "W") + { + writer.WritePropertyName("version"u8); + writer.WriteStringValue(Version); + } + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + if (Optional.IsCollectionDefined(Tags)) + { + writer.WritePropertyName("tags"u8); + writer.WriteStartObject(); + foreach (var item in Tags) + { + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + DatasetVersion 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(DatasetVersion)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDatasetVersion(document.RootElement, options); + } + + internal static DatasetVersion DeserializeDatasetVersion(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 "uri_file": return FileDatasetVersion.DeserializeFileDatasetVersion(element, options); + case "uri_folder": return FolderDatasetVersion.DeserializeFolderDatasetVersion(element, options); + } + } + return UnknownDatasetVersion.DeserializeUnknownDatasetVersion(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(DatasetVersion)} does not support writing '{options.Format}' format."); + } + } + + DatasetVersion 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDatasetVersion(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DatasetVersion)} 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 DatasetVersion FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDatasetVersion(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/ai/Azure.AI.Projects.OneDP/src/Generated/DatasetVersion.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/DatasetVersion.cs new file mode 100644 index 000000000000..cefd86f144b6 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/DatasetVersion.cs @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + /// + /// DatasetVersion Definition + /// 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 DatasetVersion + { + /// + /// 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 . + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + /// is null. + protected DatasetVersion(string datasetUri) + { + Argument.AssertNotNull(datasetUri, nameof(datasetUri)); + + DatasetUri = datasetUri; + Tags = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + /// Dataset type. + /// Indicates if dataset is reference only or managed by dataset service. If true, the underlying data will be deleted when the dataset version is deleted. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Keeps track of any properties unknown to the library. + internal DatasetVersion(string datasetUri, DatasetType type, bool? isReference, string stage, string id, string name, string version, string description, IDictionary tags, IDictionary serializedAdditionalRawData) + { + DatasetUri = datasetUri; + Type = type; + IsReference = isReference; + Stage = stage; + Id = id; + Name = name; + Version = version; + Description = description; + Tags = tags; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DatasetVersion() + { + } + + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + public string DatasetUri { get; set; } + /// Dataset type. + internal DatasetType Type { get; set; } + /// Indicates if dataset is reference only or managed by dataset service. If true, the underlying data will be deleted when the dataset version is deleted. + public bool? IsReference { get; } + /// Asset stage. + public string Stage { get; set; } + /// A unique identifier for the asset, assetId probably?. + public string Id { get; } + /// The name of the resource. + public string Name { get; } + /// The version of the resource. + public string Version { get; } + /// The asset description text. + public string Description { get; set; } + /// Tag dictionary. Tags can be added, removed, and updated. + public IDictionary Tags { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Datasets.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Datasets.cs new file mode 100644 index 000000000000..117e10a7e5e8 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Datasets.cs @@ -0,0 +1,1109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.Projects.OneDP +{ + // Data plane generated sub-client. + /// The Datasets sub-client. + public partial class Datasets + { + private const string AuthorizationHeader = "Authorization"; + private readonly AzureKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + 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 Datasets for mocking. + protected Datasets() + { + } + + /// Initializes a new instance of Datasets. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The key credential to copy. + /// The token credential to copy. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// The API version to use for this operation. + internal Datasets(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _keyCredential = keyCredential; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Get the specific version of the DatasetVersion. + /// The name of the resource. + /// The specific version id of the DatasetVersion 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> GetVersionAsync(string name, string version, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetVersionAsync(name, version, context).ConfigureAwait(false); + return Response.FromValue(DatasetVersion.FromResponse(response), response); + } + + /// Get the specific version of the DatasetVersion. + /// The name of the resource. + /// The specific version id of the DatasetVersion 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 GetVersion(string name, string version, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetVersion(name, version, context); + return Response.FromValue(DatasetVersion.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get the specific version of the DatasetVersion + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the DatasetVersion 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. + /// Service returned a non-success status code. + /// The response returned from the service. + public virtual async Task GetVersionAsync(string name, string version, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.GetVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateGetVersionRequest(name, version, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get the specific version of the DatasetVersion + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the DatasetVersion 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. + /// Service returned a non-success status code. + /// The response returned from the service. + public virtual Response GetVersion(string name, string version, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.GetVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateGetVersionRequest(name, version, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Delete the specific version of the DatasetVersion + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The name of the resource. + /// The version of the DatasetVersion 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. + /// Service returned a non-success status code. + /// The response returned from the service. + public virtual async Task DeleteVersionAsync(string name, string version, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.DeleteVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteVersionRequest(name, version, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Delete the specific version of the DatasetVersion + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The name of the resource. + /// The version of the DatasetVersion 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. + /// Service returned a non-success status code. + /// The response returned from the service. + public virtual Response DeleteVersion(string name, string version, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.DeleteVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteVersionRequest(name, version, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Create a new or replace an existing DatasetVersion with the given version id. + /// The name of the resource. + /// The specific version id of the DatasetVersion to create or replace. + /// The definition of the DatasetVersion to create. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> CreateVersionAsync(string name, string version, DatasetVersion body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateVersionAsync(name, version, content, context).ConfigureAwait(false); + return Response.FromValue(DatasetVersion.FromResponse(response), response); + } + + /// Create a new or replace an existing DatasetVersion with the given version id. + /// The name of the resource. + /// The specific version id of the DatasetVersion to create or replace. + /// The definition of the DatasetVersion to create. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response CreateVersion(string name, string version, DatasetVersion body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateVersion(name, version, content, context); + return Response.FromValue(DatasetVersion.FromResponse(response), response); + } + + /// + /// [Protocol Method] Create a new or replace an existing DatasetVersion with the given version id + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the DatasetVersion to create or replace. + /// 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. + public virtual async Task CreateVersionAsync(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.CreateVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateVersionRequest(name, version, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create a new or replace an existing DatasetVersion with the given version id + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the DatasetVersion to create or replace. + /// 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. + public virtual Response CreateVersion(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.CreateVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateVersionRequest(name, version, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create a new or update an existing DatasetVersion with the given version id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The name of the resource. + /// The specific version id of the DatasetVersion to create or replace. + /// 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. + public virtual async Task CreateOrUpdateVersionAsync(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.CreateOrUpdateVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateVersionRequest(name, version, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create a new or update an existing DatasetVersion with the given version id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The name of the resource. + /// The specific version id of the DatasetVersion to create or replace. + /// 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. + public virtual Response CreateOrUpdateVersion(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.CreateOrUpdateVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateVersionRequest(name, version, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Start a new or get an existing pending upload of a dataset for a specific version. + /// The name of the resource. + /// The specific version id of the DatasetVersion to operate on. + /// Parameters for the action. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> StartPendingUploadVersionAsync(string name, string version, PendingUploadRequest body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await StartPendingUploadVersionAsync(name, version, content, context).ConfigureAwait(false); + return Response.FromValue(PendingUploadResponse.FromResponse(response), response); + } + + /// Start a new or get an existing pending upload of a dataset for a specific version. + /// The name of the resource. + /// The specific version id of the DatasetVersion to operate on. + /// Parameters for the action. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response StartPendingUploadVersion(string name, string version, PendingUploadRequest body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = StartPendingUploadVersion(name, version, content, context); + return Response.FromValue(PendingUploadResponse.FromResponse(response), response); + } + + /// + /// [Protocol Method] Start a new or get an existing pending upload of a dataset for a specific version. + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the DatasetVersion to operate 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. + /// , 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. + public virtual async Task StartPendingUploadVersionAsync(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.StartPendingUploadVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateStartPendingUploadVersionRequest(name, version, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Start a new or get an existing pending upload of a dataset for a specific version. + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the DatasetVersion to operate 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. + /// , 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. + public virtual Response StartPendingUploadVersion(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.StartPendingUploadVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateStartPendingUploadVersionRequest(name, version, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Get download sas for dataset version. + /// The name of the resource. + /// The specific version id of the DatasetVersion to operate on. + /// Parameters for the action. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetCredentialsAsync(string name, string version, GetCredentialsRequest body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetCredentialsAsync(name, version, content, context).ConfigureAwait(false); + return Response.FromValue(AssetCredentialResponse.FromResponse(response), response); + } + + /// Get download sas for dataset version. + /// The name of the resource. + /// The specific version id of the DatasetVersion to operate on. + /// Parameters for the action. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetCredentials(string name, string version, GetCredentialsRequest body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetCredentials(name, version, content, context); + return Response.FromValue(AssetCredentialResponse.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get download sas for dataset version. + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the DatasetVersion to operate 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. + /// , 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. + public virtual async Task GetCredentialsAsync(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.GetCredentials"); + scope.Start(); + try + { + using HttpMessage message = CreateGetCredentialsRequest(name, version, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get download sas for dataset version. + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the DatasetVersion to operate 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. + /// , 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. + public virtual Response GetCredentials(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Datasets.GetCredentials"); + scope.Start(); + try + { + using HttpMessage message = CreateGetCredentialsRequest(name, version, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// List all versions of the given DatasetVersion. + /// The name of the resource. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual AsyncPageable GetVersionsAsync(string name, int? maxCount = null, string skip = null, string tags = null, ListViewType? listViewType = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetVersionsRequest(name, maxCount, skip, tags, listViewType?.ToString(), context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetVersionsNextPageRequest(nextLink, name, maxCount, skip, tags, listViewType?.ToString(), context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => DatasetVersion.DeserializeDatasetVersion(e), ClientDiagnostics, _pipeline, "Datasets.GetVersions", "value", "nextLink", context); + } + + /// List all versions of the given DatasetVersion. + /// The name of the resource. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Pageable GetVersions(string name, int? maxCount = null, string skip = null, string tags = null, ListViewType? listViewType = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetVersionsRequest(name, maxCount, skip, tags, listViewType?.ToString(), context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetVersionsNextPageRequest(nextLink, name, maxCount, skip, tags, listViewType?.ToString(), context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => DatasetVersion.DeserializeDatasetVersion(e), ClientDiagnostics, _pipeline, "Datasets.GetVersions", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List all versions of the given DatasetVersion + /// + /// + /// + /// 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 name of the resource. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. Allowed values: "ActiveOnly" | "ArchivedOnly" | "All". + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual AsyncPageable GetVersionsAsync(string name, int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetVersionsRequest(name, maxCount, skip, tags, listViewType, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetVersionsNextPageRequest(nextLink, name, maxCount, skip, tags, listViewType, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Datasets.GetVersions", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List all versions of the given DatasetVersion + /// + /// + /// + /// 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 name of the resource. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. Allowed values: "ActiveOnly" | "ArchivedOnly" | "All". + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual Pageable GetVersions(string name, int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetVersionsRequest(name, maxCount, skip, tags, listViewType, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetVersionsNextPageRequest(nextLink, name, maxCount, skip, tags, listViewType, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Datasets.GetVersions", "value", "nextLink", context); + } + + /// List the latest version of each DatasetVersion. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. + /// The cancellation token to use. + public virtual AsyncPageable GetLatestsAsync(int? maxCount = null, string skip = null, string tags = null, ListViewType? listViewType = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetLatestsRequest(maxCount, skip, tags, listViewType?.ToString(), context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetLatestsNextPageRequest(nextLink, maxCount, skip, tags, listViewType?.ToString(), context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => DatasetVersion.DeserializeDatasetVersion(e), ClientDiagnostics, _pipeline, "Datasets.GetLatests", "value", "nextLink", context); + } + + /// List the latest version of each DatasetVersion. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. + /// The cancellation token to use. + public virtual Pageable GetLatests(int? maxCount = null, string skip = null, string tags = null, ListViewType? listViewType = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetLatestsRequest(maxCount, skip, tags, listViewType?.ToString(), context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetLatestsNextPageRequest(nextLink, maxCount, skip, tags, listViewType?.ToString(), context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => DatasetVersion.DeserializeDatasetVersion(e), ClientDiagnostics, _pipeline, "Datasets.GetLatests", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List the latest version of each DatasetVersion + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. Allowed values: "ActiveOnly" | "ArchivedOnly" | "All". + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual AsyncPageable GetLatestsAsync(int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetLatestsRequest(maxCount, skip, tags, listViewType, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetLatestsNextPageRequest(nextLink, maxCount, skip, tags, listViewType, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Datasets.GetLatests", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List the latest version of each DatasetVersion + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. Allowed values: "ActiveOnly" | "ArchivedOnly" | "All". + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual Pageable GetLatests(int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetLatestsRequest(maxCount, skip, tags, listViewType, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetLatestsNextPageRequest(nextLink, maxCount, skip, tags, listViewType, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Datasets.GetLatests", "value", "nextLink", context); + } + + internal HttpMessage CreateGetVersionsRequest(string name, int? maxCount, string skip, string tags, string listViewType, 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("/datasets/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip, true); + } + if (tags != null) + { + uri.AppendQuery("tags", tags, true); + } + if (listViewType != null) + { + uri.AppendQuery("listViewType", listViewType, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetLatestsRequest(int? maxCount, string skip, string tags, string listViewType, 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("/datasets", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip, true); + } + if (tags != null) + { + uri.AppendQuery("tags", tags, true); + } + if (listViewType != null) + { + uri.AppendQuery("listViewType", listViewType, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetVersionRequest(string name, string version, 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("/datasets/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions/", false); + uri.AppendPath(version, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteVersionRequest(string name, string version, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/datasets/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions/", false); + uri.AppendPath(version, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateVersionRequest(string name, string version, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/datasets/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions/", false); + uri.AppendPath(version, true); + 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 CreateCreateOrUpdateVersionRequest(string name, string version, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/datasets/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions/", false); + uri.AppendPath(version, true); + 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 CreateStartPendingUploadVersionRequest(string name, string version, 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("/datasets/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions/", false); + uri.AppendPath(version, true); + uri.AppendPath("/startPendingUpload", 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 CreateGetCredentialsRequest(string name, string version, 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("/datasets/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions/", false); + uri.AppendPath(version, true); + uri.AppendPath("/credentials", 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 CreateGetVersionsNextPageRequest(string nextLink, string name, int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetLatestsNextPageRequest(string nextLink, int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, 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 _responseClassifier204; + private static ResponseClassifier ResponseClassifier204 => _responseClassifier204 ??= new StatusCodeClassifier(stackalloc ushort[] { 204 }); + private static ResponseClassifier _responseClassifier200201; + private static ResponseClassifier ResponseClassifier200201 => _responseClassifier200201 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 201 }); + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Deployment.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Deployment.Serialization.cs new file mode 100644 index 000000000000..efbc294a3bd7 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Deployment.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.Text.Json; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + [PersistableModelProxy(typeof(UnknownDeployment))] + public partial class Deployment : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Deployment)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W") + { + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Deployment 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(Deployment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDeployment(document.RootElement, options); + } + + internal static Deployment DeserializeDeployment(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 "ModelDeployment": return ModelDeployment.DeserializeModelDeployment(element, options); + } + } + return UnknownDeployment.DeserializeUnknownDeployment(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(Deployment)} does not support writing '{options.Format}' format."); + } + } + + Deployment 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDeployment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Deployment)} 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 Deployment FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDeployment(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/ai/Azure.AI.Projects.OneDP/src/Generated/Deployment.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Deployment.cs new file mode 100644 index 000000000000..6f223fa8644d --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Deployment.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.Projects.OneDP +{ + /// + /// Model Deployment Definition + /// 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 Deployment + { + /// + /// 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 Deployment() + { + } + + /// Initializes a new instance of . + /// The type of the deployment. + /// Name of the deployment. + /// Keeps track of any properties unknown to the library. + internal Deployment(DeploymentType type, string name, IDictionary serializedAdditionalRawData) + { + Type = type; + Name = name; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The type of the deployment. + internal DeploymentType Type { get; set; } + /// Name of the deployment. + public string Name { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/DeploymentType.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/DeploymentType.cs new file mode 100644 index 000000000000..175f083ba827 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/DeploymentType.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.Projects.OneDP +{ + /// The DeploymentType. + internal readonly partial struct DeploymentType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DeploymentType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ModelDeploymentValue = "ModelDeployment"; + + /// Model deployment. + public static DeploymentType ModelDeployment { get; } = new DeploymentType(ModelDeploymentValue); + /// Determines if two values are the same. + public static bool operator ==(DeploymentType left, DeploymentType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DeploymentType left, DeploymentType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DeploymentType(string value) => new DeploymentType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DeploymentType other && Equals(other); + /// + public bool Equals(DeploymentType 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/ai/Azure.AI.Projects.OneDP/src/Generated/Deployments.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Deployments.cs new file mode 100644 index 000000000000..501f96a9fb6b --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Deployments.cs @@ -0,0 +1,335 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.Projects.OneDP +{ + // Data plane generated sub-client. + /// The Deployments sub-client. + public partial class Deployments + { + private const string AuthorizationHeader = "Authorization"; + private readonly AzureKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + 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 Deployments for mocking. + protected Deployments() + { + } + + /// Initializes a new instance of Deployments. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The key credential to copy. + /// The token credential to copy. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// The API version to use for this operation. + internal Deployments(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _keyCredential = keyCredential; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Get a deployed model. + /// Name of the deployment. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetDeploymentAsync(string name, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetDeploymentAsync(name, context).ConfigureAwait(false); + return Response.FromValue(Deployment.FromResponse(response), response); + } + + /// Get a deployed model. + /// Name of the deployment. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetDeployment(string name, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetDeployment(name, context); + return Response.FromValue(Deployment.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get a deployed model. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Name of the deployment. + /// 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. + public virtual async Task GetDeploymentAsync(string name, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + using var scope = ClientDiagnostics.CreateScope("Deployments.GetDeployment"); + scope.Start(); + try + { + using HttpMessage message = CreateGetDeploymentRequest(name, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get a deployed model. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Name of the deployment. + /// 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. + public virtual Response GetDeployment(string name, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + using var scope = ClientDiagnostics.CreateScope("Deployments.GetDeployment"); + scope.Start(); + try + { + using HttpMessage message = CreateGetDeploymentRequest(name, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// List all deployed models in the project. + /// Model publisher to filter models by. + /// Model name (the publisher specific name) to filter models by. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + public virtual AsyncPageable GetDeploymentsAsync(string modelPublisher = null, string modelName = null, int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetDeploymentsRequest(modelPublisher, modelName, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetDeploymentsNextPageRequest(nextLink, modelPublisher, modelName, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => Deployment.DeserializeDeployment(e), ClientDiagnostics, _pipeline, "Deployments.GetDeployments", "value", "nextLink", maxpagesize, context); + } + + /// List all deployed models in the project. + /// Model publisher to filter models by. + /// Model name (the publisher specific name) to filter models by. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + public virtual Pageable GetDeployments(string modelPublisher = null, string modelName = null, int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetDeploymentsRequest(modelPublisher, modelName, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetDeploymentsNextPageRequest(nextLink, modelPublisher, modelName, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => Deployment.DeserializeDeployment(e), ClientDiagnostics, _pipeline, "Deployments.GetDeployments", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List all deployed models in the project + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Model publisher to filter models by. + /// Model name (the publisher specific name) to filter models by. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual AsyncPageable GetDeploymentsAsync(string modelPublisher, string modelName, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetDeploymentsRequest(modelPublisher, modelName, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetDeploymentsNextPageRequest(nextLink, modelPublisher, modelName, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Deployments.GetDeployments", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List all deployed models in the project + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Model publisher to filter models by. + /// Model name (the publisher specific name) to filter models by. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual Pageable GetDeployments(string modelPublisher, string modelName, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetDeploymentsRequest(modelPublisher, modelName, maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetDeploymentsNextPageRequest(nextLink, modelPublisher, modelName, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Deployments.GetDeployments", "value", "nextLink", maxpagesize, context); + } + + internal HttpMessage CreateGetDeploymentRequest(string name, 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("/deployments/", false); + uri.AppendPath(name, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetDeploymentsRequest(string modelPublisher, string modelName, int? maxCount, int? skip, int? maxpagesize, 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("/deployments", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (modelPublisher != null) + { + uri.AppendQuery("modelPublisher", modelPublisher, true); + } + if (modelName != null) + { + uri.AppendQuery("modelName", modelName, true); + } + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetDeploymentsNextPageRequest(string nextLink, string modelPublisher, string modelName, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, 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 }); + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EmbeddingConfiguration.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EmbeddingConfiguration.Serialization.cs new file mode 100644 index 000000000000..8ffb1362179c --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EmbeddingConfiguration.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.Projects.OneDP +{ + public partial class EmbeddingConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmbeddingConfiguration)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("modelDeploymentName"u8); + writer.WriteStringValue(ModelDeploymentName); + writer.WritePropertyName("embeddingField"u8); + writer.WriteStringValue(EmbeddingField); + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + EmbeddingConfiguration 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(EmbeddingConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEmbeddingConfiguration(document.RootElement, options); + } + + internal static EmbeddingConfiguration DeserializeEmbeddingConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string modelDeploymentName = default; + string embeddingField = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("modelDeploymentName"u8)) + { + modelDeploymentName = property.Value.GetString(); + continue; + } + if (property.NameEquals("embeddingField"u8)) + { + embeddingField = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EmbeddingConfiguration(modelDeploymentName, embeddingField, 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(EmbeddingConfiguration)} does not support writing '{options.Format}' format."); + } + } + + EmbeddingConfiguration 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEmbeddingConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EmbeddingConfiguration)} 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 EmbeddingConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEmbeddingConfiguration(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/ai/Azure.AI.Projects.OneDP/src/Generated/EmbeddingConfiguration.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EmbeddingConfiguration.cs new file mode 100644 index 000000000000..b4c9213fda10 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EmbeddingConfiguration.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.Projects.OneDP +{ + /// Embedding configuration class. + public partial class EmbeddingConfiguration + { + /// + /// 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 . + /// Deployment name of embedding model. It can point to a model deployment either in the parent AIServices or a connection. + /// Embedding field. + /// or is null. + public EmbeddingConfiguration(string modelDeploymentName, string embeddingField) + { + Argument.AssertNotNull(modelDeploymentName, nameof(modelDeploymentName)); + Argument.AssertNotNull(embeddingField, nameof(embeddingField)); + + ModelDeploymentName = modelDeploymentName; + EmbeddingField = embeddingField; + } + + /// Initializes a new instance of . + /// Deployment name of embedding model. It can point to a model deployment either in the parent AIServices or a connection. + /// Embedding field. + /// Keeps track of any properties unknown to the library. + internal EmbeddingConfiguration(string modelDeploymentName, string embeddingField, IDictionary serializedAdditionalRawData) + { + ModelDeploymentName = modelDeploymentName; + EmbeddingField = embeddingField; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EmbeddingConfiguration() + { + } + + /// Deployment name of embedding model. It can point to a model deployment either in the parent AIServices or a connection. + public string ModelDeploymentName { get; set; } + /// Embedding field. + public string EmbeddingField { get; set; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EntraIDCredentials.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EntraIDCredentials.Serialization.cs new file mode 100644 index 000000000000..92d91e30a178 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EntraIDCredentials.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.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + public partial class EntraIDCredentials : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EntraIDCredentials)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + EntraIDCredentials 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(EntraIDCredentials)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEntraIDCredentials(document.RootElement, options); + } + + internal static EntraIDCredentials DeserializeEntraIDCredentials(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CredentialType authType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("authType"u8)) + { + authType = new CredentialType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EntraIDCredentials(authType, 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(EntraIDCredentials)} does not support writing '{options.Format}' format."); + } + } + + EntraIDCredentials 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEntraIDCredentials(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EntraIDCredentials)} 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 EntraIDCredentials FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEntraIDCredentials(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/ai/Azure.AI.Projects.OneDP/src/Generated/EntraIDCredentials.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EntraIDCredentials.cs new file mode 100644 index 000000000000..7c7c38005040 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EntraIDCredentials.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.Projects.OneDP +{ + /// Entra ID credential definition. + public partial class EntraIDCredentials : BaseCredentials + { + /// Initializes a new instance of . + internal EntraIDCredentials() + { + AuthType = CredentialType.EntraId; + } + + /// Initializes a new instance of . + /// The type of credential used by the connection. + /// Keeps track of any properties unknown to the library. + internal EntraIDCredentials(CredentialType authType, IDictionary serializedAdditionalRawData) : base(authType, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Evaluation.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Evaluation.Serialization.cs new file mode 100644 index 000000000000..1503fd8624a0 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Evaluation.Serialization.cs @@ -0,0 +1,266 @@ +// 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.Projects.OneDP +{ + public partial class Evaluation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Evaluation)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + writer.WritePropertyName("data"u8); + writer.WriteObjectValue(Data, options); + if (Optional.IsDefined(DisplayName)) + { + writer.WritePropertyName("displayName"u8); + writer.WriteStringValue(DisplayName); + } + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + if (options.Format != "W" && Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status); + } + if (Optional.IsCollectionDefined(Tags)) + { + writer.WritePropertyName("tags"u8); + writer.WriteStartObject(); + foreach (var item in Tags) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsCollectionDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteStartObject(); + foreach (var item in Properties) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + writer.WritePropertyName("evaluators"u8); + writer.WriteStartObject(); + foreach (var item in Evaluators) + { + writer.WritePropertyName(item.Key); + writer.WriteObjectValue(item.Value, options); + } + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Evaluation 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(Evaluation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEvaluation(document.RootElement, options); + } + + internal static Evaluation DeserializeEvaluation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + InputData data = default; + string displayName = default; + string description = default; + string status = default; + IDictionary tags = default; + IDictionary properties = default; + IDictionary evaluators = 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("data"u8)) + { + data = InputData.DeserializeInputData(property.Value, options); + continue; + } + if (property.NameEquals("displayName"u8)) + { + displayName = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + status = property.Value.GetString(); + continue; + } + if (property.NameEquals("tags"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()); + } + tags = dictionary; + continue; + } + if (property.NameEquals("properties"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()); + } + properties = dictionary; + continue; + } + if (property.NameEquals("evaluators"u8)) + { + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, EvaluatorConfiguration.DeserializeEvaluatorConfiguration(property0.Value, options)); + } + evaluators = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Evaluation( + id, + data, + displayName, + description, + status, + tags ?? new ChangeTrackingDictionary(), + properties ?? new ChangeTrackingDictionary(), + evaluators, + 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(Evaluation)} does not support writing '{options.Format}' format."); + } + } + + Evaluation 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEvaluation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Evaluation)} 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 Evaluation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEvaluation(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/ai/Azure.AI.Projects.OneDP/src/Generated/Evaluation.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Evaluation.cs new file mode 100644 index 000000000000..c73c134620d1 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Evaluation.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.Projects.OneDP +{ + /// Evaluation Definition. + public partial class Evaluation + { + /// + /// 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 . + /// + /// Data for evaluation. + /// 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 . + /// + /// Evaluators to be used for the evaluation. + /// or is null. + public Evaluation(InputData data, IDictionary evaluators) + { + Argument.AssertNotNull(data, nameof(data)); + Argument.AssertNotNull(evaluators, nameof(evaluators)); + + Data = data; + Tags = new ChangeTrackingDictionary(); + Properties = new ChangeTrackingDictionary(); + Evaluators = evaluators; + } + + /// Initializes a new instance of . + /// Identifier of the evaluation. + /// + /// Data for evaluation. + /// 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 . + /// + /// Display Name for evaluation. It helps to find the evaluation easily in AI Foundry. It does not need to be unique. + /// Description of the evaluation. It can be used to store additional information about the evaluation and is mutable. + /// Status of the evaluation. It is set by service and is read-only. + /// Evaluation's tags. Unlike properties, tags are fully mutable. + /// Evaluation's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// Evaluators to be used for the evaluation. + /// Keeps track of any properties unknown to the library. + internal Evaluation(string id, InputData data, string displayName, string description, string status, IDictionary tags, IDictionary properties, IDictionary evaluators, IDictionary serializedAdditionalRawData) + { + Id = id; + Data = data; + DisplayName = displayName; + Description = description; + Status = status; + Tags = tags; + Properties = properties; + Evaluators = evaluators; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Evaluation() + { + } + + /// Identifier of the evaluation. + public string Id { get; } + /// + /// Data for evaluation. + /// 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 InputData Data { get; set; } + /// Display Name for evaluation. It helps to find the evaluation easily in AI Foundry. It does not need to be unique. + public string DisplayName { get; set; } + /// Description of the evaluation. It can be used to store additional information about the evaluation and is mutable. + public string Description { get; set; } + /// Status of the evaluation. It is set by service and is read-only. + public string Status { get; } + /// Evaluation's tags. Unlike properties, tags are fully mutable. + public IDictionary Tags { get; } + /// Evaluation's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + public IDictionary Properties { get; } + /// Evaluators to be used for the evaluation. + public IDictionary Evaluators { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Evaluations.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Evaluations.cs new file mode 100644 index 000000000000..15c3922d2e47 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Evaluations.cs @@ -0,0 +1,441 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.Projects.OneDP +{ + // Data plane generated sub-client. + /// The Evaluations sub-client. + public partial class Evaluations + { + private const string AuthorizationHeader = "Authorization"; + private readonly AzureKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + 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 Evaluations for mocking. + protected Evaluations() + { + } + + /// Initializes a new instance of Evaluations. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The key credential to copy. + /// The token credential to copy. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// The API version to use for this operation. + internal Evaluations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _keyCredential = keyCredential; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Get an evaluation run by name. + /// Identifier of the evaluation. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetEvaluationAsync(string name, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetEvaluationAsync(name, context).ConfigureAwait(false); + return Response.FromValue(Evaluation.FromResponse(response), response); + } + + /// Get an evaluation run by name. + /// Identifier of the evaluation. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetEvaluation(string name, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetEvaluation(name, context); + return Response.FromValue(Evaluation.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get an evaluation run by name. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Identifier of the evaluation. + /// 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. + public virtual async Task GetEvaluationAsync(string name, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + using var scope = ClientDiagnostics.CreateScope("Evaluations.GetEvaluation"); + scope.Start(); + try + { + using HttpMessage message = CreateGetEvaluationRequest(name, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get an evaluation run by name. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Identifier of the evaluation. + /// 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. + public virtual Response GetEvaluation(string name, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + using var scope = ClientDiagnostics.CreateScope("Evaluations.GetEvaluation"); + scope.Start(); + try + { + using HttpMessage message = CreateGetEvaluationRequest(name, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Creates an evaluation run. + /// Evaluation to be run. + /// The cancellation token to use. + /// is null. + public virtual async Task> CreateRunAsync(Evaluation evaluation, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(evaluation, nameof(evaluation)); + + using RequestContent content = evaluation.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateRunAsync(content, context).ConfigureAwait(false); + return Response.FromValue(Evaluation.FromResponse(response), response); + } + + /// Creates an evaluation run. + /// Evaluation to be run. + /// The cancellation token to use. + /// is null. + public virtual Response CreateRun(Evaluation evaluation, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(evaluation, nameof(evaluation)); + + using RequestContent content = evaluation.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateRun(content, context); + return Response.FromValue(Evaluation.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates an evaluation 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 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. + public virtual async Task CreateRunAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Evaluations.CreateRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateRunRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates an evaluation 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 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. + public virtual Response CreateRun(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Evaluations.CreateRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateRunRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// List evaluation runs. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + public virtual AsyncPageable GetEvaluationsAsync(int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetEvaluationsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetEvaluationsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => Evaluation.DeserializeEvaluation(e), ClientDiagnostics, _pipeline, "Evaluations.GetEvaluations", "value", "nextLink", maxpagesize, context); + } + + /// List evaluation runs. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + public virtual Pageable GetEvaluations(int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetEvaluationsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetEvaluationsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => Evaluation.DeserializeEvaluation(e), ClientDiagnostics, _pipeline, "Evaluations.GetEvaluations", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List evaluation runs + /// + /// + /// + /// 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 number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual AsyncPageable GetEvaluationsAsync(int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetEvaluationsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetEvaluationsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Evaluations.GetEvaluations", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List evaluation runs + /// + /// + /// + /// 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 number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual Pageable GetEvaluations(int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetEvaluationsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetEvaluationsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Evaluations.GetEvaluations", "value", "nextLink", maxpagesize, context); + } + + internal HttpMessage CreateGetEvaluationRequest(string name, 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("/evaluations/runs/", false); + uri.AppendPath(name, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetEvaluationsRequest(int? maxCount, int? skip, int? maxpagesize, 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("/evaluations/runs", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateRunRequest(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.AppendPath("/evaluations/runs:run", 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 CreateGetEvaluationsNextPageRequest(string nextLink, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, 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/ai/Azure.AI.Projects.OneDP/src/Generated/EvaluatorConfiguration.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EvaluatorConfiguration.Serialization.cs new file mode 100644 index 000000000000..0affbc74f720 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EvaluatorConfiguration.Serialization.cs @@ -0,0 +1,213 @@ +// 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.Projects.OneDP +{ + public partial class EvaluatorConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EvaluatorConfiguration)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + if (Optional.IsCollectionDefined(InitParams)) + { + writer.WritePropertyName("initParams"u8); + writer.WriteStartObject(); + foreach (var item in InitParams) + { + writer.WritePropertyName(item.Key); + if (item.Value == null) + { + writer.WriteNullValue(); + continue; + } +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + writer.WriteEndObject(); + } + if (Optional.IsCollectionDefined(DataMapping)) + { + writer.WritePropertyName("dataMapping"u8); + writer.WriteStartObject(); + foreach (var item in DataMapping) + { + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + EvaluatorConfiguration 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(EvaluatorConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEvaluatorConfiguration(document.RootElement, options); + } + + internal static EvaluatorConfiguration DeserializeEvaluatorConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + IDictionary initParams = default; + IDictionary dataMapping = 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("initParams"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(property0.Name, null); + } + else + { + dictionary.Add(property0.Name, BinaryData.FromString(property0.Value.GetRawText())); + } + } + initParams = dictionary; + continue; + } + if (property.NameEquals("dataMapping"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()); + } + dataMapping = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EvaluatorConfiguration(id, initParams ?? new ChangeTrackingDictionary(), dataMapping ?? 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(EvaluatorConfiguration)} does not support writing '{options.Format}' format."); + } + } + + EvaluatorConfiguration 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEvaluatorConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EvaluatorConfiguration)} 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 EvaluatorConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEvaluatorConfiguration(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/ai/Azure.AI.Projects.OneDP/src/Generated/EvaluatorConfiguration.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EvaluatorConfiguration.cs new file mode 100644 index 000000000000..10492f8d1165 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/EvaluatorConfiguration.cs @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + /// Evaluator Configuration. + public partial class EvaluatorConfiguration + { + /// + /// 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 . + /// Identifier of the evaluator. + /// is null. + public EvaluatorConfiguration(string id) + { + Argument.AssertNotNull(id, nameof(id)); + + Id = id; + InitParams = new ChangeTrackingDictionary(); + DataMapping = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// Identifier of the evaluator. + /// Initialization parameters of the evaluator. + /// Data parameters of the evaluator. + /// Keeps track of any properties unknown to the library. + internal EvaluatorConfiguration(string id, IDictionary initParams, IDictionary dataMapping, IDictionary serializedAdditionalRawData) + { + Id = id; + InitParams = initParams; + DataMapping = dataMapping; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EvaluatorConfiguration() + { + } + + /// Identifier of the evaluator. + public string Id { get; set; } + /// + /// Initialization parameters of the evaluator. + /// + /// 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" }. + /// + /// + /// + /// + public IDictionary InitParams { get; } + /// Data parameters of the evaluator. + public IDictionary DataMapping { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/FileDatasetVersion.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/FileDatasetVersion.Serialization.cs new file mode 100644 index 000000000000..5b27cb377f79 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/FileDatasetVersion.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.Projects.OneDP +{ + public partial class FileDatasetVersion : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileDatasetVersion)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("openAIPurpose"u8); + writer.WriteStringValue(OpenAIPurpose); + } + + FileDatasetVersion 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(FileDatasetVersion)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileDatasetVersion(document.RootElement, options); + } + + internal static FileDatasetVersion DeserializeFileDatasetVersion(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string openAIPurpose = default; + string datasetUri = default; + DatasetType type = default; + bool? isReference = default; + string stage = default; + string id = default; + string name = default; + string version = default; + string description = default; + IDictionary tags = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("openAIPurpose"u8)) + { + openAIPurpose = property.Value.GetString(); + continue; + } + if (property.NameEquals("datasetUri"u8)) + { + datasetUri = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new DatasetType(property.Value.GetString()); + continue; + } + if (property.NameEquals("isReference"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + isReference = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stage"u8)) + { + stage = property.Value.GetString(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("version"u8)) + { + version = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("tags"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()); + } + tags = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileDatasetVersion( + datasetUri, + type, + isReference, + stage, + id, + name, + version, + description, + tags ?? new ChangeTrackingDictionary(), + serializedAdditionalRawData, + openAIPurpose); + } + + 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(FileDatasetVersion)} does not support writing '{options.Format}' format."); + } + } + + FileDatasetVersion 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileDatasetVersion(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileDatasetVersion)} 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 FileDatasetVersion FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileDatasetVersion(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/ai/Azure.AI.Projects.OneDP/src/Generated/FileDatasetVersion.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/FileDatasetVersion.cs new file mode 100644 index 000000000000..ed3cb63143fe --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/FileDatasetVersion.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + /// FileDatasetVersion Definition. + public partial class FileDatasetVersion : DatasetVersion + { + /// Initializes a new instance of . + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + /// Indicates OpenAI Purpose. FileDatasets created with this field will be compatible with OpenAI-specific features. + /// or is null. + public FileDatasetVersion(string datasetUri, string openAIPurpose) : base(datasetUri) + { + Argument.AssertNotNull(datasetUri, nameof(datasetUri)); + Argument.AssertNotNull(openAIPurpose, nameof(openAIPurpose)); + + Type = DatasetType.UriFile; + OpenAIPurpose = openAIPurpose; + } + + /// Initializes a new instance of . + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + /// Dataset type. + /// Indicates if dataset is reference only or managed by dataset service. If true, the underlying data will be deleted when the dataset version is deleted. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Keeps track of any properties unknown to the library. + /// Indicates OpenAI Purpose. FileDatasets created with this field will be compatible with OpenAI-specific features. + internal FileDatasetVersion(string datasetUri, DatasetType type, bool? isReference, string stage, string id, string name, string version, string description, IDictionary tags, IDictionary serializedAdditionalRawData, string openAIPurpose) : base(datasetUri, type, isReference, stage, id, name, version, description, tags, serializedAdditionalRawData) + { + OpenAIPurpose = openAIPurpose; + } + + /// Initializes a new instance of for deserialization. + internal FileDatasetVersion() + { + } + + /// Indicates OpenAI Purpose. FileDatasets created with this field will be compatible with OpenAI-specific features. + public string OpenAIPurpose { get; set; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/FolderDatasetVersion.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/FolderDatasetVersion.Serialization.cs new file mode 100644 index 000000000000..942bfd012f0b --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/FolderDatasetVersion.Serialization.cs @@ -0,0 +1,197 @@ +// 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.Projects.OneDP +{ + public partial class FolderDatasetVersion : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FolderDatasetVersion)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + FolderDatasetVersion 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(FolderDatasetVersion)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFolderDatasetVersion(document.RootElement, options); + } + + internal static FolderDatasetVersion DeserializeFolderDatasetVersion(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string datasetUri = default; + DatasetType type = default; + bool? isReference = default; + string stage = default; + string id = default; + string name = default; + string version = default; + string description = default; + IDictionary tags = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("datasetUri"u8)) + { + datasetUri = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new DatasetType(property.Value.GetString()); + continue; + } + if (property.NameEquals("isReference"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + isReference = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stage"u8)) + { + stage = property.Value.GetString(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("version"u8)) + { + version = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("tags"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()); + } + tags = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FolderDatasetVersion( + datasetUri, + type, + isReference, + stage, + id, + name, + version, + description, + tags ?? 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(FolderDatasetVersion)} does not support writing '{options.Format}' format."); + } + } + + FolderDatasetVersion 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFolderDatasetVersion(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FolderDatasetVersion)} 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 FolderDatasetVersion FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFolderDatasetVersion(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/ai/Azure.AI.Projects.OneDP/src/Generated/FolderDatasetVersion.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/FolderDatasetVersion.cs new file mode 100644 index 000000000000..bbfb905e640e --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/FolderDatasetVersion.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.Projects.OneDP +{ + /// FileDatasetVersion Definition. + public partial class FolderDatasetVersion : DatasetVersion + { + /// Initializes a new instance of . + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + /// is null. + public FolderDatasetVersion(string datasetUri) : base(datasetUri) + { + Argument.AssertNotNull(datasetUri, nameof(datasetUri)); + + Type = DatasetType.UriFolder; + } + + /// Initializes a new instance of . + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + /// Dataset type. + /// Indicates if dataset is reference only or managed by dataset service. If true, the underlying data will be deleted when the dataset version is deleted. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Keeps track of any properties unknown to the library. + internal FolderDatasetVersion(string datasetUri, DatasetType type, bool? isReference, string stage, string id, string name, string version, string description, IDictionary tags, IDictionary serializedAdditionalRawData) : base(datasetUri, type, isReference, stage, id, name, version, description, tags, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal FolderDatasetVersion() + { + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/GetCredentialsRequest.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/GetCredentialsRequest.Serialization.cs new file mode 100644 index 000000000000..fdd9b80f32c8 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/GetCredentialsRequest.Serialization.cs @@ -0,0 +1,134 @@ +// 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.Projects.OneDP +{ + public partial class GetCredentialsRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(GetCredentialsRequest)} does not support writing '{format}' format."); + } + + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + GetCredentialsRequest 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(GetCredentialsRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeGetCredentialsRequest(document.RootElement, options); + } + + internal static GetCredentialsRequest DeserializeGetCredentialsRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new GetCredentialsRequest(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(GetCredentialsRequest)} does not support writing '{options.Format}' format."); + } + } + + GetCredentialsRequest 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeGetCredentialsRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(GetCredentialsRequest)} 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 GetCredentialsRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeGetCredentialsRequest(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/ai/Azure.AI.Projects.OneDP/src/Generated/GetCredentialsRequest.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/GetCredentialsRequest.cs new file mode 100644 index 000000000000..42eb5574a1cb --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/GetCredentialsRequest.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + /// The GetCredentialsRequest. + public partial class GetCredentialsRequest + { + /// + /// 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 GetCredentialsRequest() + { + } + + /// Initializes a new instance of . + /// Keeps track of any properties unknown to the library. + internal GetCredentialsRequest(IDictionary serializedAdditionalRawData) + { + _serializedAdditionalRawData = serializedAdditionalRawData; + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Index.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Index.Serialization.cs new file mode 100644 index 000000000000..0d8d86b12d26 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Index.Serialization.cs @@ -0,0 +1,171 @@ +// 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.Projects.OneDP +{ + [PersistableModelProxy(typeof(UnknownIndex))] + public partial class Index : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Index)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (Optional.IsDefined(Stage)) + { + writer.WritePropertyName("stage"u8); + writer.WriteStringValue(Stage); + } + if (options.Format != "W" && Optional.IsDefined(Id)) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (options.Format != "W") + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (options.Format != "W") + { + writer.WritePropertyName("version"u8); + writer.WriteStringValue(Version); + } + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + if (Optional.IsCollectionDefined(Tags)) + { + writer.WritePropertyName("tags"u8); + writer.WriteStartObject(); + foreach (var item in Tags) + { + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Index 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(Index)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeIndex(document.RootElement, options); + } + + internal static Index DeserializeIndex(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 "AzureSearch": return AzureAISearchIndex.DeserializeAzureAISearchIndex(element, options); + case "CosmosDBNoSqlVectorStore": return CosmosDBIndex.DeserializeCosmosDBIndex(element, options); + case "ManagedAzureSearch": return ManagedAzureAISearchIndex.DeserializeManagedAzureAISearchIndex(element, options); + } + } + return UnknownIndex.DeserializeUnknownIndex(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(Index)} does not support writing '{options.Format}' format."); + } + } + + Index 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeIndex(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Index)} 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 Index FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeIndex(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/ai/Azure.AI.Projects.OneDP/src/Generated/Index.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Index.cs new file mode 100644 index 000000000000..4149c8a2c137 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Index.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.Projects.OneDP +{ + /// + /// Index resource Definition + /// 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 Index + { + /// + /// 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 Index() + { + Tags = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// Type of index. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Keeps track of any properties unknown to the library. + internal Index(IndexType type, string stage, string id, string name, string version, string description, IDictionary tags, IDictionary serializedAdditionalRawData) + { + Type = type; + Stage = stage; + Id = id; + Name = name; + Version = version; + Description = description; + Tags = tags; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Type of index. + internal IndexType Type { get; set; } + /// Asset stage. + public string Stage { get; set; } + /// A unique identifier for the asset, assetId probably?. + public string Id { get; } + /// The name of the resource. + public string Name { get; } + /// The version of the resource. + public string Version { get; } + /// The asset description text. + public string Description { get; set; } + /// Tag dictionary. Tags can be added, removed, and updated. + public IDictionary Tags { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/IndexType.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/IndexType.cs new file mode 100644 index 000000000000..39a83be231ee --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/IndexType.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.Projects.OneDP +{ + /// The IndexType. + internal readonly partial struct IndexType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public IndexType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AzureSearchValue = "AzureSearch"; + private const string CosmosDBValue = "CosmosDBNoSqlVectorStore"; + private const string ManagedAzureSearchValue = "ManagedAzureSearch"; + + /// Azure search. + public static IndexType AzureSearch { get; } = new IndexType(AzureSearchValue); + /// CosmosDB. + public static IndexType CosmosDB { get; } = new IndexType(CosmosDBValue); + /// Managed Azure Search. + public static IndexType ManagedAzureSearch { get; } = new IndexType(ManagedAzureSearchValue); + /// Determines if two values are the same. + public static bool operator ==(IndexType left, IndexType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(IndexType left, IndexType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator IndexType(string value) => new IndexType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is IndexType other && Equals(other); + /// + public bool Equals(IndexType 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/ai/Azure.AI.Projects.OneDP/src/Generated/Indexes.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Indexes.cs new file mode 100644 index 000000000000..2c3f44144897 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Indexes.cs @@ -0,0 +1,821 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.Projects.OneDP +{ + // Data plane generated sub-client. + /// The Indexes sub-client. + public partial class Indexes + { + private const string AuthorizationHeader = "Authorization"; + private readonly AzureKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + 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 Indexes for mocking. + protected Indexes() + { + } + + /// Initializes a new instance of Indexes. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The key credential to copy. + /// The token credential to copy. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// The API version to use for this operation. + internal Indexes(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _keyCredential = keyCredential; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Get the specific version of the Index. + /// The name of the resource. + /// The specific version id of the Index 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> GetVersionAsync(string name, string version, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetVersionAsync(name, version, context).ConfigureAwait(false); + return Response.FromValue(Index.FromResponse(response), response); + } + + /// Get the specific version of the Index. + /// The name of the resource. + /// The specific version id of the Index 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 GetVersion(string name, string version, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetVersion(name, version, context); + return Response.FromValue(Index.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get the specific version of the Index + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the Index 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. + /// Service returned a non-success status code. + /// The response returned from the service. + public virtual async Task GetVersionAsync(string name, string version, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + using var scope = ClientDiagnostics.CreateScope("Indexes.GetVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateGetVersionRequest(name, version, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get the specific version of the Index + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the Index 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. + /// Service returned a non-success status code. + /// The response returned from the service. + public virtual Response GetVersion(string name, string version, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + using var scope = ClientDiagnostics.CreateScope("Indexes.GetVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateGetVersionRequest(name, version, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Delete the specific version of the Index + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The name of the resource. + /// The version of the Index 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. + /// Service returned a non-success status code. + /// The response returned from the service. + public virtual async Task DeleteVersionAsync(string name, string version, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + using var scope = ClientDiagnostics.CreateScope("Indexes.DeleteVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteVersionRequest(name, version, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Delete the specific version of the Index + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The name of the resource. + /// The version of the Index 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. + /// Service returned a non-success status code. + /// The response returned from the service. + public virtual Response DeleteVersion(string name, string version, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + + using var scope = ClientDiagnostics.CreateScope("Indexes.DeleteVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteVersionRequest(name, version, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Create a new or replace an existing Index with the given version id. + /// The name of the resource. + /// The specific version id of the Index to create or replace. + /// The definition of the Index to create. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> CreateVersionAsync(string name, string version, Index body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateVersionAsync(name, version, content, context).ConfigureAwait(false); + return Response.FromValue(Index.FromResponse(response), response); + } + + /// Create a new or replace an existing Index with the given version id. + /// The name of the resource. + /// The specific version id of the Index to create or replace. + /// The definition of the Index to create. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response CreateVersion(string name, string version, Index body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateVersion(name, version, content, context); + return Response.FromValue(Index.FromResponse(response), response); + } + + /// + /// [Protocol Method] Create a new or replace an existing Index with the given version id + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the Index to create or replace. + /// 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. + public virtual async Task CreateVersionAsync(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Indexes.CreateVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateVersionRequest(name, version, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create a new or replace an existing Index with the given version id + /// + /// + /// + /// 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 name of the resource. + /// The specific version id of the Index to create or replace. + /// 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. + public virtual Response CreateVersion(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Indexes.CreateVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateVersionRequest(name, version, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create a new or update an existing Index with the given version id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The name of the resource. + /// The specific version id of the Index to create or replace. + /// 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. + public virtual async Task CreateOrUpdateVersionAsync(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Indexes.CreateOrUpdateVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateVersionRequest(name, version, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create a new or update an existing Index with the given version id + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The name of the resource. + /// The specific version id of the Index to create or replace. + /// 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. + public virtual Response CreateOrUpdateVersion(string name, string version, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNullOrEmpty(version, nameof(version)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Indexes.CreateOrUpdateVersion"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateVersionRequest(name, version, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// List all versions of the given Index. + /// The name of the resource. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual AsyncPageable GetVersionsAsync(string name, int? maxCount = null, string skip = null, string tags = null, ListViewType? listViewType = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetVersionsRequest(name, maxCount, skip, tags, listViewType?.ToString(), context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetVersionsNextPageRequest(nextLink, name, maxCount, skip, tags, listViewType?.ToString(), context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => Index.DeserializeIndex(e), ClientDiagnostics, _pipeline, "Indexes.GetVersions", "value", "nextLink", context); + } + + /// List all versions of the given Index. + /// The name of the resource. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Pageable GetVersions(string name, int? maxCount = null, string skip = null, string tags = null, ListViewType? listViewType = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetVersionsRequest(name, maxCount, skip, tags, listViewType?.ToString(), context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetVersionsNextPageRequest(nextLink, name, maxCount, skip, tags, listViewType?.ToString(), context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => Index.DeserializeIndex(e), ClientDiagnostics, _pipeline, "Indexes.GetVersions", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List all versions of the given Index + /// + /// + /// + /// 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 name of the resource. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. Allowed values: "ActiveOnly" | "ArchivedOnly" | "All". + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual AsyncPageable GetVersionsAsync(string name, int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetVersionsRequest(name, maxCount, skip, tags, listViewType, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetVersionsNextPageRequest(nextLink, name, maxCount, skip, tags, listViewType, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Indexes.GetVersions", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List all versions of the given Index + /// + /// + /// + /// 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 name of the resource. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. Allowed values: "ActiveOnly" | "ArchivedOnly" | "All". + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual Pageable GetVersions(string name, int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetVersionsRequest(name, maxCount, skip, tags, listViewType, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetVersionsNextPageRequest(nextLink, name, maxCount, skip, tags, listViewType, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Indexes.GetVersions", "value", "nextLink", context); + } + + /// List the latest version of each Index. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. + /// The cancellation token to use. + public virtual AsyncPageable GetLatestsAsync(int? maxCount = null, string skip = null, string tags = null, ListViewType? listViewType = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetLatestsRequest(maxCount, skip, tags, listViewType?.ToString(), context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetLatestsNextPageRequest(nextLink, maxCount, skip, tags, listViewType?.ToString(), context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => Index.DeserializeIndex(e), ClientDiagnostics, _pipeline, "Indexes.GetLatests", "value", "nextLink", context); + } + + /// List the latest version of each Index. + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. + /// The cancellation token to use. + public virtual Pageable GetLatests(int? maxCount = null, string skip = null, string tags = null, ListViewType? listViewType = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetLatestsRequest(maxCount, skip, tags, listViewType?.ToString(), context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetLatestsNextPageRequest(nextLink, maxCount, skip, tags, listViewType?.ToString(), context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => Index.DeserializeIndex(e), ClientDiagnostics, _pipeline, "Indexes.GetLatests", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List the latest version of each Index + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. Allowed values: "ActiveOnly" | "ArchivedOnly" | "All". + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual AsyncPageable GetLatestsAsync(int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetLatestsRequest(maxCount, skip, tags, listViewType, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetLatestsNextPageRequest(nextLink, maxCount, skip, tags, listViewType, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Indexes.GetLatests", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List the latest version of each Index + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. + /// Continuation token for pagination. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] View type for including/excluding (for example) archived entities. Allowed values: "ActiveOnly" | "ArchivedOnly" | "All". + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual Pageable GetLatests(int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetLatestsRequest(maxCount, skip, tags, listViewType, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetLatestsNextPageRequest(nextLink, maxCount, skip, tags, listViewType, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Indexes.GetLatests", "value", "nextLink", context); + } + + internal HttpMessage CreateGetVersionsRequest(string name, int? maxCount, string skip, string tags, string listViewType, 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("/indexes/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip, true); + } + if (tags != null) + { + uri.AppendQuery("tags", tags, true); + } + if (listViewType != null) + { + uri.AppendQuery("listViewType", listViewType, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetLatestsRequest(int? maxCount, string skip, string tags, string listViewType, 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("/indexes", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip, true); + } + if (tags != null) + { + uri.AppendQuery("tags", tags, true); + } + if (listViewType != null) + { + uri.AppendQuery("listViewType", listViewType, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetVersionRequest(string name, string version, 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("/indexes/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions/", false); + uri.AppendPath(version, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteVersionRequest(string name, string version, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/indexes/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions/", false); + uri.AppendPath(version, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateVersionRequest(string name, string version, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/indexes/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions/", false); + uri.AppendPath(version, true); + 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 CreateCreateOrUpdateVersionRequest(string name, string version, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/indexes/", false); + uri.AppendPath(name, true); + uri.AppendPath("/versions/", false); + uri.AppendPath(version, true); + 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 CreateGetVersionsNextPageRequest(string nextLink, string name, int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetLatestsNextPageRequest(string nextLink, int? maxCount, string skip, string tags, string listViewType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, 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 _responseClassifier204; + private static ResponseClassifier ResponseClassifier204 => _responseClassifier204 ??= new StatusCodeClassifier(stackalloc ushort[] { 204 }); + private static ResponseClassifier _responseClassifier200201; + private static ResponseClassifier ResponseClassifier200201 => _responseClassifier200201 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 201 }); + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/InputData.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/InputData.Serialization.cs new file mode 100644 index 000000000000..3772ce645f20 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/InputData.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.Projects.OneDP +{ + [PersistableModelProxy(typeof(UnknownInputData))] + public partial class InputData : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InputData)} does not support writing '{format}' format."); + } + + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + InputData 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(InputData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInputData(document.RootElement, options); + } + + internal static InputData DeserializeInputData(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 "dataset": return InputDataset.DeserializeInputDataset(element, options); + } + } + return UnknownInputData.DeserializeUnknownInputData(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(InputData)} does not support writing '{options.Format}' format."); + } + } + + InputData 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeInputData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InputData)} 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 InputData FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeInputData(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/ai/Azure.AI.Projects.OneDP/src/Generated/InputData.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/InputData.cs new file mode 100644 index 000000000000..a36ded9d09e5 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/InputData.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.Projects.OneDP +{ + /// + /// Abstract data class. + /// 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 InputData + { + /// + /// 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 InputData() + { + } + + /// Initializes a new instance of . + /// Type of the data. + /// Keeps track of any properties unknown to the library. + internal InputData(string type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Type of the data. + internal string Type { get; set; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/InputDataset.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/InputDataset.Serialization.cs new file mode 100644 index 000000000000..ce3d476d0289 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/InputDataset.Serialization.cs @@ -0,0 +1,134 @@ +// 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.Projects.OneDP +{ + public partial class InputDataset : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InputDataset)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + + InputDataset 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(InputDataset)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInputDataset(document.RootElement, options); + } + + internal static InputDataset DeserializeInputDataset(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + string type = 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("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InputDataset(type, serializedAdditionalRawData, id); + } + + 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(InputDataset)} does not support writing '{options.Format}' format."); + } + } + + InputDataset 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeInputDataset(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InputDataset)} 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 InputDataset FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeInputDataset(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/ai/Azure.AI.Projects.OneDP/src/Generated/InputDataset.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/InputDataset.cs new file mode 100644 index 000000000000..8a3b357b6090 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/InputDataset.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.Projects.OneDP +{ + /// Dataset as source for evaluation. + public partial class InputDataset : InputData + { + /// Initializes a new instance of . + /// Evaluation input data. + /// is null. + public InputDataset(string id) + { + Argument.AssertNotNull(id, nameof(id)); + + Type = "dataset"; + Id = id; + } + + /// Initializes a new instance of . + /// Type of the data. + /// Keeps track of any properties unknown to the library. + /// Evaluation input data. + internal InputDataset(string type, IDictionary serializedAdditionalRawData, string id) : base(type, serializedAdditionalRawData) + { + Id = id; + } + + /// Initializes a new instance of for deserialization. + internal InputDataset() + { + } + + /// Evaluation input data. + public string Id { get; set; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal.cs new file mode 100644 index 000000000000..8f97d844401d --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.Projects.OneDP +{ + // Data plane generated sub-client. + /// The Internal sub-client. + public partial class Internal + { + private const string AuthorizationHeader = "Authorization"; + private readonly AzureKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + private static readonly string[] AuthorizationScopes = new string[] { "https://cognitiveservices.azure.com/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + + /// 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 Internal for mocking. + protected Internal() + { + } + + /// Initializes a new instance of Internal. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The key credential to copy. + /// The token credential to copy. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + internal Internal(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _keyCredential = keyCredential; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/Argument.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/Argument.cs new file mode 100644 index 000000000000..3a95ec218792 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + internal static class Argument + { + public static void AssertNotNull(T value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNull(T? value, string name) + where T : struct + { + if (!value.HasValue) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNullOrEmpty(IEnumerable value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value is ICollection collectionOfT && collectionOfT.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + if (value is ICollection collection && collection.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + using IEnumerator e = value.GetEnumerator(); + if (!e.MoveNext()) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + } + + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value.Length == 0) + { + throw new ArgumentException("Value cannot be an empty string.", name); + } + } + + public static void AssertNotNullOrWhiteSpace(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); + } + } + + public static void AssertNotDefault(ref T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + throw new ArgumentException("Value cannot be empty.", name); + } + } + + public static void AssertInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (minimum.CompareTo(value) > 0) + { + throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); + } + if (maximum.CompareTo(value) < 0) + { + throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); + } + } + + public static void AssertEnumDefined(Type enumType, object value, string name) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); + } + } + + public static T CheckNotNull(T value, string name) + where T : class + { + AssertNotNull(value, name); + return value; + } + + public static string CheckNotNullOrEmpty(string value, string name) + { + AssertNotNullOrEmpty(value, name); + return value; + } + + public static void AssertNull(T value, string name, string message = null) + { + if (value != null) + { + throw new ArgumentException(message ?? "Value must be null.", name); + } + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 000000000000..6063557c10d9 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + { + private IDictionary _innerDictionary; + + public ChangeTrackingDictionary() + { + } + + public ChangeTrackingDictionary(IDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(dictionary); + } + + public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(); + foreach (var pair in dictionary) + { + _innerDictionary.Add(pair); + } + } + + public bool IsUndefined => _innerDictionary == null; + + public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + + public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + + public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + + public TValue this[TKey key] + { + get + { + if (IsUndefined) + { + throw new KeyNotFoundException(nameof(key)); + } + return EnsureDictionary()[key]; + } + set + { + EnsureDictionary()[key] = value; + } + } + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public IEnumerator> GetEnumerator() + { + if (IsUndefined) + { + IEnumerator> enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureDictionary().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + EnsureDictionary().Add(item); + } + + public void Clear() + { + EnsureDictionary().Clear(); + } + + public bool Contains(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (IsUndefined) + { + return; + } + EnsureDictionary().CopyTo(array, index); + } + + public bool Remove(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(item); + } + + public void Add(TKey key, TValue value) + { + EnsureDictionary().Add(key, value); + } + + public bool ContainsKey(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().ContainsKey(key); + } + + public bool Remove(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (IsUndefined) + { + value = default; + return false; + } + return EnsureDictionary().TryGetValue(key, out value); + } + + public IDictionary EnsureDictionary() + { + return _innerDictionary ??= new Dictionary(); + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/ChangeTrackingList.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 000000000000..170b6bb22347 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.Projects.OneDP +{ + internal class ChangeTrackingList : IList, IReadOnlyList + { + private IList _innerList; + + public ChangeTrackingList() + { + } + + public ChangeTrackingList(IList innerList) + { + if (innerList != null) + { + _innerList = innerList; + } + } + + public ChangeTrackingList(IReadOnlyList innerList) + { + if (innerList != null) + { + _innerList = innerList.ToList(); + } + } + + public bool IsUndefined => _innerList == null; + + public int Count => IsUndefined ? 0 : EnsureList().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + + public T this[int index] + { + get + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return EnsureList()[index]; + } + set + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList()[index] = value; + } + } + + public void Reset() + { + _innerList = null; + } + + public IEnumerator GetEnumerator() + { + if (IsUndefined) + { + IEnumerator enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureList().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(T item) + { + EnsureList().Add(item); + } + + public void Clear() + { + EnsureList().Clear(); + } + + public bool Contains(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (IsUndefined) + { + return; + } + EnsureList().CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Remove(item); + } + + public int IndexOf(T item) + { + if (IsUndefined) + { + return -1; + } + return EnsureList().IndexOf(item); + } + + public void Insert(int index, T item) + { + EnsureList().Insert(index, item); + } + + public void RemoveAt(int index) + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList().RemoveAt(index); + } + + public IList EnsureList() + { + return _innerList ??= new List(); + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 000000000000..c354798cd985 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,399 @@ +// 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.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + internal static class ModelSerializationExtensions + { + internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; + internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); + + public static object GetObject(this JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.String: + return element.GetString(); + case JsonValueKind.Number: + if (element.TryGetInt32(out int intValue)) + { + return intValue; + } + if (element.TryGetInt64(out long longValue)) + { + return longValue; + } + return element.GetDouble(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Undefined: + case JsonValueKind.Null: + return null; + case JsonValueKind.Object: + var dictionary = new Dictionary(); + foreach (var jsonProperty in element.EnumerateObject()) + { + dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); + } + return dictionary; + case JsonValueKind.Array: + var list = new List(); + foreach (var item in element.EnumerateArray()) + { + list.Add(item.GetObject()); + } + return list.ToArray(); + default: + throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); + } + } + + public static byte[] GetBytesFromBase64(this JsonElement element, string format) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + + return format switch + { + "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), + "D" => element.GetBytesFromBase64(), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + } + + public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch + { + "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), + _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) + }; + + public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); + + public static char GetChar(this JsonElement element) + { + if (element.ValueKind == JsonValueKind.String) + { + var text = element.GetString(); + if (text == null || text.Length != 1) + { + throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); + } + return text[0]; + } + else + { + throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); + } + } + + [Conditional("DEBUG")] + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + { + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + } + + public static string GetRequiredString(this JsonElement element) + { + var value = element.GetString(); + if (value == null) + { + throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); + } + return value; + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, char value) + { + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + switch (format) + { + case "U": + writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); + break; + case "D": + writer.WriteBase64StringValue(value); + break; + default: + throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); + } + } + + public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + if (format != "U") + { + throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); + } + writer.WriteNumberValue(value.ToUnixTimeSeconds()); + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; + case byte[] bytes: + writer.WriteBase64StringValue(bytes); + break; + case BinaryData bytes0: + writer.WriteBase64StringValue(bytes0); + break; + case JsonElement json: + json.WriteTo(writer); + break; + case int i: + writer.WriteNumberValue(i); + break; + case decimal d: + writer.WriteNumberValue(d); + break; + case double d0: + if (double.IsNaN(d0)) + { + writer.WriteStringValue("NaN"); + } + else + { + writer.WriteNumberValue(d0); + } + break; + case float f: + writer.WriteNumberValue(f); + break; + case long l: + writer.WriteNumberValue(l); + break; + case string s: + writer.WriteStringValue(s); + break; + case bool b: + writer.WriteBooleanValue(b); + break; + case Guid g: + writer.WriteStringValue(g); + break; + case DateTimeOffset dateTimeOffset: + writer.WriteStringValue(dateTimeOffset, "O"); + break; + case DateTime dateTime: + writer.WriteStringValue(dateTime, "O"); + break; + case IEnumerable> enumerable: + writer.WriteStartObject(); + foreach (var pair in enumerable) + { + writer.WritePropertyName(pair.Key); + writer.WriteObjectValue(pair.Value, options); + } + writer.WriteEndObject(); + break; + case IEnumerable objectEnumerable: + writer.WriteStartArray(); + foreach (var item in objectEnumerable) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + break; + case TimeSpan timeSpan: + writer.WriteStringValue(timeSpan, "P"); + break; + default: + throw new NotSupportedException($"Not supported type {value.GetType()}"); + } + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) + { + writer.WriteObjectValue(value, options); + } + + internal static class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. 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 + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/Optional.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/Optional.cs new file mode 100644 index 000000000000..0c7fa3e8c3b4 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; + +namespace Azure.AI.Projects.OneDP +{ + internal static class Optional + { + public static bool IsCollectionDefined(IEnumerable collection) + { + return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); + } + + public static bool IsCollectionDefined(IDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsCollectionDefined(IReadOnlyDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsDefined(T? value) + where T : struct + { + return value.HasValue; + } + + public static bool IsDefined(object value) + { + return value != null; + } + + public static bool IsDefined(JsonElement value) + { + return value.ValueKind != JsonValueKind.Undefined; + } + + public static bool IsDefined(string value) + { + return value != null; + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 000000000000..46730667bd96 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + internal class Utf8JsonRequestContent : RequestContent + { + private readonly MemoryStream _stream; + private readonly RequestContent _content; + + public Utf8JsonRequestContent() + { + _stream = new MemoryStream(); + _content = Create(_stream); + JsonWriter = new Utf8JsonWriter(_stream); + } + + public Utf8JsonWriter JsonWriter { get; } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { + await JsonWriter.FlushAsync().ConfigureAwait(false); + await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { + JsonWriter.Flush(); + _content.WriteTo(stream, cancellationToken); + } + + public override bool TryComputeLength(out long length) + { + length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; + return true; + } + + public override void Dispose() + { + JsonWriter.Dispose(); + _content.Dispose(); + _stream.Dispose(); + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ListViewType.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ListViewType.cs new file mode 100644 index 000000000000..3dbd14873aea --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ListViewType.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.Projects.OneDP +{ + /// List View Type Definition. + public readonly partial struct ListViewType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ListViewType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ActiveOnlyValue = "ActiveOnly"; + private const string ArchivedOnlyValue = "ArchivedOnly"; + private const string AllValue = "All"; + + /// List only active items. + public static ListViewType ActiveOnly { get; } = new ListViewType(ActiveOnlyValue); + /// List only archived items. + public static ListViewType ArchivedOnly { get; } = new ListViewType(ArchivedOnlyValue); + /// List all items. + public static ListViewType All { get; } = new ListViewType(AllValue); + /// Determines if two values are the same. + public static bool operator ==(ListViewType left, ListViewType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ListViewType left, ListViewType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ListViewType(string value) => new ListViewType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ListViewType other && Equals(other); + /// + public bool Equals(ListViewType 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/ai/Azure.AI.Projects.OneDP/src/Generated/ManagedAzureAISearchIndex.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ManagedAzureAISearchIndex.Serialization.cs new file mode 100644 index 000000000000..f185c51bbd5c --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ManagedAzureAISearchIndex.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.Projects.OneDP +{ + public partial class ManagedAzureAISearchIndex : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ManagedAzureAISearchIndex)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("vectorStoreId"u8); + writer.WriteStringValue(VectorStoreId); + } + + ManagedAzureAISearchIndex 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(ManagedAzureAISearchIndex)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeManagedAzureAISearchIndex(document.RootElement, options); + } + + internal static ManagedAzureAISearchIndex DeserializeManagedAzureAISearchIndex(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string vectorStoreId = default; + IndexType type = default; + string stage = default; + string id = default; + string name = default; + string version = default; + string description = default; + IDictionary tags = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("vectorStoreId"u8)) + { + vectorStoreId = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new IndexType(property.Value.GetString()); + continue; + } + if (property.NameEquals("stage"u8)) + { + stage = property.Value.GetString(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("version"u8)) + { + version = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("tags"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()); + } + tags = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ManagedAzureAISearchIndex( + type, + stage, + id, + name, + version, + description, + tags ?? new ChangeTrackingDictionary(), + serializedAdditionalRawData, + vectorStoreId); + } + + 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(ManagedAzureAISearchIndex)} does not support writing '{options.Format}' format."); + } + } + + ManagedAzureAISearchIndex 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeManagedAzureAISearchIndex(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ManagedAzureAISearchIndex)} 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 ManagedAzureAISearchIndex FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeManagedAzureAISearchIndex(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/ai/Azure.AI.Projects.OneDP/src/Generated/ManagedAzureAISearchIndex.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ManagedAzureAISearchIndex.cs new file mode 100644 index 000000000000..ecb6fe7d5607 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ManagedAzureAISearchIndex.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.Projects.OneDP +{ + /// Managed Azure AI Search Index Definition. + public partial class ManagedAzureAISearchIndex : Index + { + /// Initializes a new instance of . + /// Vector store id of managed index. + /// is null. + public ManagedAzureAISearchIndex(string vectorStoreId) + { + Argument.AssertNotNull(vectorStoreId, nameof(vectorStoreId)); + + Type = IndexType.ManagedAzureSearch; + VectorStoreId = vectorStoreId; + } + + /// Initializes a new instance of . + /// Type of index. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Keeps track of any properties unknown to the library. + /// Vector store id of managed index. + internal ManagedAzureAISearchIndex(IndexType type, string stage, string id, string name, string version, string description, IDictionary tags, IDictionary serializedAdditionalRawData, string vectorStoreId) : base(type, stage, id, name, version, description, tags, serializedAdditionalRawData) + { + VectorStoreId = vectorStoreId; + } + + /// Initializes a new instance of for deserialization. + internal ManagedAzureAISearchIndex() + { + } + + /// Vector store id of managed index. + public string VectorStoreId { get; set; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ModelDeployment.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ModelDeployment.Serialization.cs new file mode 100644 index 000000000000..4902bdc1c08f --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ModelDeployment.Serialization.cs @@ -0,0 +1,218 @@ +// 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.Projects.OneDP +{ + public partial class ModelDeployment : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ModelDeployment)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (options.Format != "W") + { + writer.WritePropertyName("modelName"u8); + writer.WriteStringValue(ModelName); + } + if (options.Format != "W") + { + writer.WritePropertyName("modelVersion"u8); + writer.WriteStringValue(ModelVersion); + } + if (options.Format != "W") + { + writer.WritePropertyName("modelPublisher"u8); + writer.WriteStringValue(ModelPublisher); + } + if (options.Format != "W") + { + writer.WritePropertyName("capabilities"u8); + writer.WriteStartObject(); + foreach (var item in Capabilities) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (options.Format != "W") + { + writer.WritePropertyName("sku"u8); + writer.WriteObjectValue(Sku, options); + } + if (options.Format != "W" && Optional.IsDefined(ConnectionName)) + { + writer.WritePropertyName("connectionName"u8); + writer.WriteStringValue(ConnectionName); + } + } + + ModelDeployment 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(ModelDeployment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeModelDeployment(document.RootElement, options); + } + + internal static ModelDeployment DeserializeModelDeployment(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string modelName = default; + string modelVersion = default; + string modelPublisher = default; + IReadOnlyDictionary capabilities = default; + Sku sku = default; + string connectionName = default; + DeploymentType type = default; + string name = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("modelName"u8)) + { + modelName = property.Value.GetString(); + continue; + } + if (property.NameEquals("modelVersion"u8)) + { + modelVersion = property.Value.GetString(); + continue; + } + if (property.NameEquals("modelPublisher"u8)) + { + modelPublisher = property.Value.GetString(); + continue; + } + if (property.NameEquals("capabilities"u8)) + { + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + capabilities = dictionary; + continue; + } + if (property.NameEquals("sku"u8)) + { + sku = Sku.DeserializeSku(property.Value, options); + continue; + } + if (property.NameEquals("connectionName"u8)) + { + connectionName = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new DeploymentType(property.Value.GetString()); + continue; + } + 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 ModelDeployment( + type, + name, + serializedAdditionalRawData, + modelName, + modelVersion, + modelPublisher, + capabilities, + sku, + connectionName); + } + + 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(ModelDeployment)} does not support writing '{options.Format}' format."); + } + } + + ModelDeployment 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeModelDeployment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ModelDeployment)} 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 ModelDeployment FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeModelDeployment(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/ai/Azure.AI.Projects.OneDP/src/Generated/ModelDeployment.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ModelDeployment.cs new file mode 100644 index 000000000000..7841f691ebe4 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ModelDeployment.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + /// Model Deployment Definition. + public partial class ModelDeployment : Deployment + { + /// Initializes a new instance of . + internal ModelDeployment() + { + Type = DeploymentType.ModelDeployment; + Capabilities = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// The type of the deployment. + /// Name of the deployment. + /// Keeps track of any properties unknown to the library. + /// Publisher-specific name of the deployed model. + /// Publisher-specific version of the deployed model. + /// Name of the deployed model's publisher. + /// Capabilities of deployed model. + /// Sku of the model deployment. + /// Name of the connection the deployment comes from. + internal ModelDeployment(DeploymentType type, string name, IDictionary serializedAdditionalRawData, string modelName, string modelVersion, string modelPublisher, IReadOnlyDictionary capabilities, Sku sku, string connectionName) : base(type, name, serializedAdditionalRawData) + { + ModelName = modelName; + ModelVersion = modelVersion; + ModelPublisher = modelPublisher; + Capabilities = capabilities; + Sku = sku; + ConnectionName = connectionName; + } + + /// Publisher-specific name of the deployed model. + public string ModelName { get; } + /// Publisher-specific version of the deployed model. + public string ModelVersion { get; } + /// Name of the deployed model's publisher. + public string ModelPublisher { get; } + /// Capabilities of deployed model. + public IReadOnlyDictionary Capabilities { get; } + /// Sku of the model deployment. + public Sku Sku { get; } + /// Name of the connection the deployment comes from. + public string ConnectionName { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/NoAuthenticationCredentials.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/NoAuthenticationCredentials.Serialization.cs new file mode 100644 index 000000000000..3e4bcd528568 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/NoAuthenticationCredentials.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.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + public partial class NoAuthenticationCredentials : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NoAuthenticationCredentials)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + NoAuthenticationCredentials 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(NoAuthenticationCredentials)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNoAuthenticationCredentials(document.RootElement, options); + } + + internal static NoAuthenticationCredentials DeserializeNoAuthenticationCredentials(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CredentialType authType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("authType"u8)) + { + authType = new CredentialType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NoAuthenticationCredentials(authType, 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(NoAuthenticationCredentials)} does not support writing '{options.Format}' format."); + } + } + + NoAuthenticationCredentials 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNoAuthenticationCredentials(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NoAuthenticationCredentials)} 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 NoAuthenticationCredentials FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNoAuthenticationCredentials(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/ai/Azure.AI.Projects.OneDP/src/Generated/NoAuthenticationCredentials.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/NoAuthenticationCredentials.cs new file mode 100644 index 000000000000..410711a89131 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/NoAuthenticationCredentials.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.Projects.OneDP +{ + /// Credentials that do not require authentication. + public partial class NoAuthenticationCredentials : BaseCredentials + { + /// Initializes a new instance of . + internal NoAuthenticationCredentials() + { + AuthType = CredentialType.None; + } + + /// Initializes a new instance of . + /// The type of credential used by the connection. + /// Keeps track of any properties unknown to the library. + internal NoAuthenticationCredentials(CredentialType authType, IDictionary serializedAdditionalRawData) : base(authType, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadRequest.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadRequest.Serialization.cs new file mode 100644 index 000000000000..4c47a8b0d525 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadRequest.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.Projects.OneDP +{ + public partial class PendingUploadRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PendingUploadRequest)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(PendingUploadId)) + { + writer.WritePropertyName("pendingUploadId"u8); + writer.WriteStringValue(PendingUploadId); + } + if (Optional.IsDefined(ConnectionName)) + { + writer.WritePropertyName("connectionName"u8); + writer.WriteStringValue(ConnectionName); + } + writer.WritePropertyName("pendingUploadType"u8); + writer.WriteStringValue(PendingUploadType.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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + PendingUploadRequest 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(PendingUploadRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePendingUploadRequest(document.RootElement, options); + } + + internal static PendingUploadRequest DeserializePendingUploadRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string pendingUploadId = default; + string connectionName = default; + PendingUploadType pendingUploadType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("pendingUploadId"u8)) + { + pendingUploadId = property.Value.GetString(); + continue; + } + if (property.NameEquals("connectionName"u8)) + { + connectionName = property.Value.GetString(); + continue; + } + if (property.NameEquals("pendingUploadType"u8)) + { + pendingUploadType = new PendingUploadType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PendingUploadRequest(pendingUploadId, connectionName, pendingUploadType, 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(PendingUploadRequest)} does not support writing '{options.Format}' format."); + } + } + + PendingUploadRequest 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePendingUploadRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PendingUploadRequest)} 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 PendingUploadRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePendingUploadRequest(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/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadRequest.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadRequest.cs new file mode 100644 index 000000000000..0ee1af04c28b --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadRequest.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.Projects.OneDP +{ + /// Represents a request for a pending upload. + public partial class PendingUploadRequest + { + /// + /// 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 PendingUploadRequest() + { + } + + /// Initializes a new instance of . + /// If PendingUploadId is not provided, a random GUID will be used. + /// Name of Azure blob storage connection to use for generating temporary SAS token. + /// TemporaryBlobReference is the only supported type. + /// Keeps track of any properties unknown to the library. + internal PendingUploadRequest(string pendingUploadId, string connectionName, PendingUploadType pendingUploadType, IDictionary serializedAdditionalRawData) + { + PendingUploadId = pendingUploadId; + ConnectionName = connectionName; + PendingUploadType = pendingUploadType; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// If PendingUploadId is not provided, a random GUID will be used. + public string PendingUploadId { get; set; } + /// Name of Azure blob storage connection to use for generating temporary SAS token. + public string ConnectionName { get; set; } + /// TemporaryBlobReference is the only supported type. + public PendingUploadType PendingUploadType { get; } = PendingUploadType.TemporaryBlobReference; + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadResponse.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadResponse.Serialization.cs new file mode 100644 index 000000000000..ac466ec650a1 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadResponse.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.Projects.OneDP +{ + public partial class PendingUploadResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PendingUploadResponse)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("blobReferenceForConsumption"u8); + writer.WriteObjectValue(BlobReferenceForConsumption, options); + writer.WritePropertyName("pendingUploadId"u8); + writer.WriteStringValue(PendingUploadId); + if (Optional.IsDefined(DatasetVersion)) + { + writer.WritePropertyName("datasetVersion"u8); + writer.WriteStringValue(DatasetVersion); + } + writer.WritePropertyName("pendingUploadType"u8); + writer.WriteStringValue(PendingUploadType.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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + PendingUploadResponse 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(PendingUploadResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePendingUploadResponse(document.RootElement, options); + } + + internal static PendingUploadResponse DeserializePendingUploadResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BlobReferenceForConsumption blobReferenceForConsumption = default; + string pendingUploadId = default; + string datasetVersion = default; + PendingUploadType pendingUploadType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("blobReferenceForConsumption"u8)) + { + blobReferenceForConsumption = BlobReferenceForConsumption.DeserializeBlobReferenceForConsumption(property.Value, options); + continue; + } + if (property.NameEquals("pendingUploadId"u8)) + { + pendingUploadId = property.Value.GetString(); + continue; + } + if (property.NameEquals("datasetVersion"u8)) + { + datasetVersion = property.Value.GetString(); + continue; + } + if (property.NameEquals("pendingUploadType"u8)) + { + pendingUploadType = new PendingUploadType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PendingUploadResponse(blobReferenceForConsumption, pendingUploadId, datasetVersion, pendingUploadType, 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(PendingUploadResponse)} does not support writing '{options.Format}' format."); + } + } + + PendingUploadResponse 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePendingUploadResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PendingUploadResponse)} 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 PendingUploadResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePendingUploadResponse(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/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadResponse.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadResponse.cs new file mode 100644 index 000000000000..5acdf2aadac5 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadResponse.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.Projects.OneDP +{ + /// Represents the response for a pending upload request. + public partial class PendingUploadResponse + { + /// + /// 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 . + /// Container-level read, write, list SAS. + /// ID for this upload request. + /// or is null. + internal PendingUploadResponse(BlobReferenceForConsumption blobReferenceForConsumption, string pendingUploadId) + { + Argument.AssertNotNull(blobReferenceForConsumption, nameof(blobReferenceForConsumption)); + Argument.AssertNotNull(pendingUploadId, nameof(pendingUploadId)); + + BlobReferenceForConsumption = blobReferenceForConsumption; + PendingUploadId = pendingUploadId; + } + + /// Initializes a new instance of . + /// Container-level read, write, list SAS. + /// ID for this upload request. + /// Version of dataset to be created if user did not specify version when initially creating upload. + /// TemporaryBlobReference is the only supported type. + /// Keeps track of any properties unknown to the library. + internal PendingUploadResponse(BlobReferenceForConsumption blobReferenceForConsumption, string pendingUploadId, string datasetVersion, PendingUploadType pendingUploadType, IDictionary serializedAdditionalRawData) + { + BlobReferenceForConsumption = blobReferenceForConsumption; + PendingUploadId = pendingUploadId; + DatasetVersion = datasetVersion; + PendingUploadType = pendingUploadType; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal PendingUploadResponse() + { + } + + /// Container-level read, write, list SAS. + public BlobReferenceForConsumption BlobReferenceForConsumption { get; } + /// ID for this upload request. + public string PendingUploadId { get; } + /// Version of dataset to be created if user did not specify version when initially creating upload. + public string DatasetVersion { get; } + /// TemporaryBlobReference is the only supported type. + public PendingUploadType PendingUploadType { get; } = PendingUploadType.TemporaryBlobReference; + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadType.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadType.cs new file mode 100644 index 000000000000..e3ce87ba0254 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/PendingUploadType.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.Projects.OneDP +{ + /// The type of pending upload. + public readonly partial struct PendingUploadType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public PendingUploadType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NoneValue = "None"; + private const string TemporaryBlobReferenceValue = "TemporaryBlobReference"; + + /// No pending upload. + public static PendingUploadType None { get; } = new PendingUploadType(NoneValue); + /// Temporary Blob Reference is the only supported type. + public static PendingUploadType TemporaryBlobReference { get; } = new PendingUploadType(TemporaryBlobReferenceValue); + /// Determines if two values are the same. + public static bool operator ==(PendingUploadType left, PendingUploadType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(PendingUploadType left, PendingUploadType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator PendingUploadType(string value) => new PendingUploadType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is PendingUploadType other && Equals(other); + /// + public bool Equals(PendingUploadType 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/ai/Azure.AI.Projects.OneDP/src/Generated/RedTeam.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/RedTeam.Serialization.cs new file mode 100644 index 000000000000..c186690e445f --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/RedTeam.Serialization.cs @@ -0,0 +1,293 @@ +// 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.Projects.OneDP +{ + public partial class RedTeam : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RedTeam)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (Optional.IsDefined(ScanName)) + { + writer.WritePropertyName("scanName"u8); + writer.WriteStringValue(ScanName); + } + writer.WritePropertyName("numTurns"u8); + writer.WriteNumberValue(NumTurns); + writer.WritePropertyName("attackStrategies"u8); + writer.WriteStartArray(); + foreach (var item in AttackStrategies) + { + writer.WriteStringValue(item.ToString()); + } + writer.WriteEndArray(); + writer.WritePropertyName("simulationOnly"u8); + writer.WriteBooleanValue(SimulationOnly); + writer.WritePropertyName("riskCategories"u8); + writer.WriteStartArray(); + foreach (var item in RiskCategories) + { + writer.WriteStringValue(item.ToString()); + } + writer.WriteEndArray(); + if (Optional.IsDefined(ApplicationScenario)) + { + writer.WritePropertyName("applicationScenario"u8); + writer.WriteStringValue(ApplicationScenario); + } + if (Optional.IsCollectionDefined(Tags)) + { + writer.WritePropertyName("tags"u8); + writer.WriteStartObject(); + foreach (var item in Tags) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsCollectionDefined(Properties)) + { + writer.WritePropertyName("properties"u8); + writer.WriteStartObject(); + foreach (var item in Properties) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (options.Format != "W" && Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status); + } + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RedTeam 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(RedTeam)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRedTeam(document.RootElement, options); + } + + internal static RedTeam DeserializeRedTeam(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + string scanName = default; + int numTurns = default; + IList attackStrategies = default; + bool simulationOnly = default; + IList riskCategories = default; + string applicationScenario = default; + IDictionary tags = default; + IDictionary properties = default; + string status = 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("scanName"u8)) + { + scanName = property.Value.GetString(); + continue; + } + if (property.NameEquals("numTurns"u8)) + { + numTurns = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("attackStrategies"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new AttackStrategy(item.GetString())); + } + attackStrategies = array; + continue; + } + if (property.NameEquals("simulationOnly"u8)) + { + simulationOnly = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("riskCategories"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new RiskCategory(item.GetString())); + } + riskCategories = array; + continue; + } + if (property.NameEquals("applicationScenario"u8)) + { + applicationScenario = property.Value.GetString(); + continue; + } + if (property.NameEquals("tags"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()); + } + tags = dictionary; + continue; + } + if (property.NameEquals("properties"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()); + } + properties = dictionary; + continue; + } + if (property.NameEquals("status"u8)) + { + status = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RedTeam( + id, + scanName, + numTurns, + attackStrategies, + simulationOnly, + riskCategories, + applicationScenario, + tags ?? new ChangeTrackingDictionary(), + properties ?? new ChangeTrackingDictionary(), + status, + 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(RedTeam)} does not support writing '{options.Format}' format."); + } + } + + RedTeam 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRedTeam(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RedTeam)} 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 RedTeam FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRedTeam(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/ai/Azure.AI.Projects.OneDP/src/Generated/RedTeam.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/RedTeam.cs new file mode 100644 index 000000000000..d34d8df86dae --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/RedTeam.cs @@ -0,0 +1,121 @@ +// 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.Projects.OneDP +{ + /// Red team details. + public partial class RedTeam + { + /// + /// 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 simulation rounds. + /// List of attack strategies or nested lists of attack strategies. + /// Simulation-only or Simulation + Evaluation. Default false, if true the scan outputs conversation not evaluation result. + /// List of risk categories to generate attack objectives for. + /// or is null. + public RedTeam(int numTurns, IEnumerable attackStrategies, bool simulationOnly, IEnumerable riskCategories) + { + Argument.AssertNotNull(attackStrategies, nameof(attackStrategies)); + Argument.AssertNotNull(riskCategories, nameof(riskCategories)); + + NumTurns = numTurns; + AttackStrategies = attackStrategies.ToList(); + SimulationOnly = simulationOnly; + RiskCategories = riskCategories.ToList(); + Tags = new ChangeTrackingDictionary(); + Properties = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// Identifier of the red team. + /// Name of the red-team scan. + /// Number of simulation rounds. + /// List of attack strategies or nested lists of attack strategies. + /// Simulation-only or Simulation + Evaluation. Default false, if true the scan outputs conversation not evaluation result. + /// List of risk categories to generate attack objectives for. + /// Application scenario for the red team operation, to generate scenario specific attacks. + /// Red team's tags. Unlike properties, tags are fully mutable. + /// Red team's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// Status of the red-team. It is set by service and is read-only. + /// Keeps track of any properties unknown to the library. + internal RedTeam(string id, string scanName, int numTurns, IList attackStrategies, bool simulationOnly, IList riskCategories, string applicationScenario, IDictionary tags, IDictionary properties, string status, IDictionary serializedAdditionalRawData) + { + Id = id; + ScanName = scanName; + NumTurns = numTurns; + AttackStrategies = attackStrategies; + SimulationOnly = simulationOnly; + RiskCategories = riskCategories; + ApplicationScenario = applicationScenario; + Tags = tags; + Properties = properties; + Status = status; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RedTeam() + { + } + + /// Identifier of the red team. + public string Id { get; } + /// Name of the red-team scan. + public string ScanName { get; set; } + /// Number of simulation rounds. + public int NumTurns { get; set; } + /// List of attack strategies or nested lists of attack strategies. + public IList AttackStrategies { get; } + /// Simulation-only or Simulation + Evaluation. Default false, if true the scan outputs conversation not evaluation result. + public bool SimulationOnly { get; set; } + /// List of risk categories to generate attack objectives for. + public IList RiskCategories { get; } + /// Application scenario for the red team operation, to generate scenario specific attacks. + public string ApplicationScenario { get; set; } + /// Red team's tags. Unlike properties, tags are fully mutable. + public IDictionary Tags { get; } + /// Red team's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + public IDictionary Properties { get; } + /// Status of the red-team. It is set by service and is read-only. + public string Status { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/RedTeams.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/RedTeams.cs new file mode 100644 index 000000000000..f8c761e22779 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/RedTeams.cs @@ -0,0 +1,441 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.Projects.OneDP +{ + // Data plane generated sub-client. + /// The RedTeams sub-client. + public partial class RedTeams + { + private const string AuthorizationHeader = "Authorization"; + private readonly AzureKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + 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 RedTeams for mocking. + protected RedTeams() + { + } + + /// Initializes a new instance of RedTeams. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The key credential to copy. + /// The token credential to copy. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + /// The API version to use for this operation. + internal RedTeams(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _keyCredential = keyCredential; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Get a redteam by name. + /// Identifier of the red team. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetRedTeamAsync(string name, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetRedTeamAsync(name, context).ConfigureAwait(false); + return Response.FromValue(RedTeam.FromResponse(response), response); + } + + /// Get a redteam by name. + /// Identifier of the red team. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetRedTeam(string name, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetRedTeam(name, context); + return Response.FromValue(RedTeam.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get a redteam by name. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Identifier of the red team. + /// 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. + public virtual async Task GetRedTeamAsync(string name, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + using var scope = ClientDiagnostics.CreateScope("RedTeams.GetRedTeam"); + scope.Start(); + try + { + using HttpMessage message = CreateGetRedTeamRequest(name, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get a redteam by name. + /// + /// + /// + /// 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. + /// + /// + /// + /// + /// Identifier of the red team. + /// 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. + public virtual Response GetRedTeam(string name, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + using var scope = ClientDiagnostics.CreateScope("RedTeams.GetRedTeam"); + scope.Start(); + try + { + using HttpMessage message = CreateGetRedTeamRequest(name, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Creates a redteam run. + /// Redteam to be run. + /// The cancellation token to use. + /// is null. + public virtual async Task> CreateRunAsync(RedTeam redTeam, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(redTeam, nameof(redTeam)); + + using RequestContent content = redTeam.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateRunAsync(content, context).ConfigureAwait(false); + return Response.FromValue(RedTeam.FromResponse(response), response); + } + + /// Creates a redteam run. + /// Redteam to be run. + /// The cancellation token to use. + /// is null. + public virtual Response CreateRun(RedTeam redTeam, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(redTeam, nameof(redTeam)); + + using RequestContent content = redTeam.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateRun(content, context); + return Response.FromValue(RedTeam.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates a redteam 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 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. + public virtual async Task CreateRunAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("RedTeams.CreateRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateRunRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates a redteam 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 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. + public virtual Response CreateRun(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("RedTeams.CreateRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateRunRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// List a redteam by name. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + public virtual AsyncPageable GetRedTeamsAsync(int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRedTeamsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRedTeamsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => RedTeam.DeserializeRedTeam(e), ClientDiagnostics, _pipeline, "RedTeams.GetRedTeams", "value", "nextLink", maxpagesize, context); + } + + /// List a redteam by name. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The cancellation token to use. + public virtual Pageable GetRedTeams(int? maxCount = null, int? skip = null, int? maxpagesize = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRedTeamsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRedTeamsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => RedTeam.DeserializeRedTeam(e), ClientDiagnostics, _pipeline, "RedTeams.GetRedTeams", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List a redteam by name. + /// + /// + /// + /// 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 number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual AsyncPageable GetRedTeamsAsync(int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRedTeamsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRedTeamsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "RedTeams.GetRedTeams", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List a redteam by name. + /// + /// + /// + /// 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 number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + public virtual Pageable GetRedTeams(int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRedTeamsRequest(maxCount, skip, pageSizeHint, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRedTeamsNextPageRequest(nextLink, maxCount, skip, pageSizeHint, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "RedTeams.GetRedTeams", "value", "nextLink", maxpagesize, context); + } + + internal HttpMessage CreateGetRedTeamRequest(string name, 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("/redTeams/runs/", false); + uri.AppendPath(name, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetRedTeamsRequest(int? maxCount, int? skip, int? maxpagesize, 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("/redTeams/runs", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateRunRequest(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.AppendPath("/redTeams/runs:run", 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 CreateGetRedTeamsNextPageRequest(string nextLink, int? maxCount, int? skip, int? maxpagesize, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, 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/ai/Azure.AI.Projects.OneDP/src/Generated/RiskCategory.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/RiskCategory.cs new file mode 100644 index 000000000000..a7b0bf7c6e34 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/RiskCategory.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.Projects.OneDP +{ + /// Risk category for the attack objective. + public readonly partial struct RiskCategory : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RiskCategory(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string HateUnfairnessValue = "HateUnfairness"; + private const string ViolenceValue = "Violence"; + private const string SexualValue = "Sexual"; + private const string SelfHarmValue = "SelfHarm"; + private const string ProtectedMaterialValue = "ProtectedMaterial"; + private const string CodeVulnerabilityValue = "CodeVulnerability"; + private const string UngroundedAttributesValue = "UngroundedAttributes"; + + /// Represents content related to hate or unfairness. + public static RiskCategory HateUnfairness { get; } = new RiskCategory(HateUnfairnessValue); + /// Represents content related to violence. + public static RiskCategory Violence { get; } = new RiskCategory(ViolenceValue); + /// Represents content of a sexual nature. + public static RiskCategory Sexual { get; } = new RiskCategory(SexualValue); + /// Represents content related to self-harm. + public static RiskCategory SelfHarm { get; } = new RiskCategory(SelfHarmValue); + /// Represents content involving protected material. + public static RiskCategory ProtectedMaterial { get; } = new RiskCategory(ProtectedMaterialValue); + /// Represents content related to code vulnerabilities. + public static RiskCategory CodeVulnerability { get; } = new RiskCategory(CodeVulnerabilityValue); + /// Represents content with ungrounded attributes. + public static RiskCategory UngroundedAttributes { get; } = new RiskCategory(UngroundedAttributesValue); + /// Determines if two values are the same. + public static bool operator ==(RiskCategory left, RiskCategory right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RiskCategory left, RiskCategory right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator RiskCategory(string value) => new RiskCategory(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RiskCategory other && Equals(other); + /// + public bool Equals(RiskCategory 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/ai/Azure.AI.Projects.OneDP/src/Generated/SASCredentials.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SASCredentials.Serialization.cs new file mode 100644 index 000000000000..527446425ab9 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SASCredentials.Serialization.cs @@ -0,0 +1,137 @@ +// 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.Projects.OneDP +{ + public partial class SASCredentials : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SASCredentials)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (options.Format != "W" && Optional.IsDefined(SasToken)) + { + writer.WritePropertyName("sasToken"u8); + writer.WriteStringValue(SasToken); + } + } + + SASCredentials 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(SASCredentials)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSASCredentials(document.RootElement, options); + } + + internal static SASCredentials DeserializeSASCredentials(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string sasToken = default; + CredentialType authType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("sasToken"u8)) + { + sasToken = property.Value.GetString(); + continue; + } + if (property.NameEquals("authType"u8)) + { + authType = new CredentialType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SASCredentials(authType, serializedAdditionalRawData, sasToken); + } + + 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(SASCredentials)} does not support writing '{options.Format}' format."); + } + } + + SASCredentials 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSASCredentials(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SASCredentials)} 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 SASCredentials FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSASCredentials(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/ai/Azure.AI.Projects.OneDP/src/Generated/SASCredentials.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SASCredentials.cs new file mode 100644 index 000000000000..0b7b9601fa04 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SASCredentials.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.Projects.OneDP +{ + /// Shared Access Signature (SAS) credential definition. + public partial class SASCredentials : BaseCredentials + { + /// Initializes a new instance of . + internal SASCredentials() + { + AuthType = CredentialType.SAS; + } + + /// Initializes a new instance of . + /// The type of credential used by the connection. + /// Keeps track of any properties unknown to the library. + /// SAS token. + internal SASCredentials(CredentialType authType, IDictionary serializedAdditionalRawData, string sasToken) : base(authType, serializedAdditionalRawData) + { + SasToken = sasToken; + } + + /// SAS token. + public string SasToken { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SasCredential.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SasCredential.Serialization.cs new file mode 100644 index 000000000000..54eb441eac21 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SasCredential.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.Projects.OneDP +{ + public partial class SasCredential : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SasCredential)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("sasUri"u8); + writer.WriteStringValue(SasUri); + } + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SasCredential 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(SasCredential)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSasCredential(document.RootElement, options); + } + + internal static SasCredential DeserializeSasCredential(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string sasUri = default; + SasCredentialType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("sasUri"u8)) + { + sasUri = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new SasCredentialType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SasCredential(sasUri, 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(SasCredential)} does not support writing '{options.Format}' format."); + } + } + + SasCredential 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSasCredential(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SasCredential)} 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 SasCredential FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSasCredential(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/ai/Azure.AI.Projects.OneDP/src/Generated/SasCredential.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SasCredential.cs new file mode 100644 index 000000000000..3d48ed334b50 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SasCredential.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.Projects.OneDP +{ + /// SAS Credential definition. + public partial class SasCredential + { + /// + /// 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 SasCredential() + { + } + + /// Initializes a new instance of . + /// SAS uri. + /// Type of credential. + /// Keeps track of any properties unknown to the library. + internal SasCredential(string sasUri, SasCredentialType type, IDictionary serializedAdditionalRawData) + { + SasUri = sasUri; + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// SAS uri. + public string SasUri { get; } + /// Type of credential. + public SasCredentialType Type { get; } = SasCredentialType.SAS; + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SasCredentialType.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SasCredentialType.cs new file mode 100644 index 000000000000..5cec0dadc671 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/SasCredentialType.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.Projects.OneDP +{ + /// The SasCredential_type. + public readonly partial struct SasCredentialType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public SasCredentialType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SASValue = "SAS"; + + /// SAS. + public static SasCredentialType SAS { get; } = new SasCredentialType(SASValue); + /// Determines if two values are the same. + public static bool operator ==(SasCredentialType left, SasCredentialType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(SasCredentialType left, SasCredentialType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator SasCredentialType(string value) => new SasCredentialType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is SasCredentialType other && Equals(other); + /// + public bool Equals(SasCredentialType 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/ai/Azure.AI.Projects.OneDP/src/Generated/ServicePatterns.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ServicePatterns.cs new file mode 100644 index 000000000000..29578c37dafe --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ServicePatterns.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.Projects.OneDP +{ + // Data plane generated sub-client. + /// The ServicePatterns sub-client. + public partial class ServicePatterns + { + private const string AuthorizationHeader = "Authorization"; + private readonly AzureKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + private static readonly string[] AuthorizationScopes = new string[] { "https://cognitiveservices.azure.com/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + + /// 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 ServicePatterns for mocking. + protected ServicePatterns() + { + } + + /// Initializes a new instance of ServicePatterns. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The key credential to copy. + /// The token credential to copy. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + internal ServicePatterns(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _keyCredential = keyCredential; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + } + + private ServicePatternsBuildingBlocks _cachedServicePatternsBuildingBlocks; + + /// Initializes a new instance of ServicePatternsBuildingBlocks. + public virtual ServicePatternsBuildingBlocks GetServicePatternsBuildingBlocksClient() + { + return Volatile.Read(ref _cachedServicePatternsBuildingBlocks) ?? Interlocked.CompareExchange(ref _cachedServicePatternsBuildingBlocks, new ServicePatternsBuildingBlocks(ClientDiagnostics, _pipeline, _keyCredential, _tokenCredential, _endpoint), null) ?? _cachedServicePatternsBuildingBlocks; + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ServicePatternsBuildingBlocks.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ServicePatternsBuildingBlocks.cs new file mode 100644 index 000000000000..fc20799e4a96 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/ServicePatternsBuildingBlocks.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.Projects.OneDP +{ + // Data plane generated sub-client. + /// The ServicePatternsBuildingBlocks sub-client. + public partial class ServicePatternsBuildingBlocks + { + private const string AuthorizationHeader = "Authorization"; + private readonly AzureKeyCredential _keyCredential; + private const string AuthorizationApiKeyPrefix = "Bearer"; + private static readonly string[] AuthorizationScopes = new string[] { "https://cognitiveservices.azure.com/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + + /// 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 ServicePatternsBuildingBlocks for mocking. + protected ServicePatternsBuildingBlocks() + { + } + + /// Initializes a new instance of ServicePatternsBuildingBlocks. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The key credential to copy. + /// The token credential to copy. + /// + /// Project endpoint. In the form "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/_project" + /// if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the form + /// "https://<your-ai-services-account-name>.services.ai.azure.com/api/projects/<your-project-name>" if you want to explicitly + /// specify the Foundry Project name. + /// + internal ServicePatternsBuildingBlocks(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _keyCredential = keyCredential; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Sku.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Sku.Serialization.cs new file mode 100644 index 000000000000..f7c2d3e3e6dd --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Sku.Serialization.cs @@ -0,0 +1,180 @@ +// 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.Projects.OneDP +{ + public partial class Sku : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Sku)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("capacity"u8); + writer.WriteNumberValue(Capacity); + writer.WritePropertyName("family"u8); + writer.WriteStringValue(Family); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + writer.WritePropertyName("size"u8); + writer.WriteStringValue(Size); + writer.WritePropertyName("tier"u8); + writer.WriteStringValue(Tier); + 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, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Sku 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(Sku)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSku(document.RootElement, options); + } + + internal static Sku DeserializeSku(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + long capacity = default; + string family = default; + string name = default; + string size = default; + string tier = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("capacity"u8)) + { + capacity = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("family"u8)) + { + family = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("size"u8)) + { + size = property.Value.GetString(); + continue; + } + if (property.NameEquals("tier"u8)) + { + tier = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Sku( + capacity, + family, + name, + size, + tier, + 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(Sku)} does not support writing '{options.Format}' format."); + } + } + + Sku 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSku(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Sku)} 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 Sku FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSku(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/ai/Azure.AI.Projects.OneDP/src/Generated/Sku.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Sku.cs new file mode 100644 index 000000000000..637332bee33d --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/Sku.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + /// Sku information. + public partial class Sku + { + /// + /// 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 . + /// Sku capacity. + /// Sku family. + /// Sku name. + /// Sku size. + /// Sku tier. + /// , , or is null. + internal Sku(long capacity, string family, string name, string size, string tier) + { + Argument.AssertNotNull(family, nameof(family)); + Argument.AssertNotNull(name, nameof(name)); + Argument.AssertNotNull(size, nameof(size)); + Argument.AssertNotNull(tier, nameof(tier)); + + Capacity = capacity; + Family = family; + Name = name; + Size = size; + Tier = tier; + } + + /// Initializes a new instance of . + /// Sku capacity. + /// Sku family. + /// Sku name. + /// Sku size. + /// Sku tier. + /// Keeps track of any properties unknown to the library. + internal Sku(long capacity, string family, string name, string size, string tier, IDictionary serializedAdditionalRawData) + { + Capacity = capacity; + Family = family; + Name = name; + Size = size; + Tier = tier; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Sku() + { + } + + /// Sku capacity. + public long Capacity { get; } + /// Sku family. + public string Family { get; } + /// Sku name. + public string Name { get; } + /// Sku size. + public string Size { get; } + /// Sku tier. + public string Tier { get; } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownBaseCredentials.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownBaseCredentials.Serialization.cs new file mode 100644 index 000000000000..97574f68a590 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownBaseCredentials.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.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + internal partial class UnknownBaseCredentials : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BaseCredentials)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + BaseCredentials 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(BaseCredentials)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBaseCredentials(document.RootElement, options); + } + + internal static UnknownBaseCredentials DeserializeUnknownBaseCredentials(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CredentialType authType = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("authType"u8)) + { + authType = new CredentialType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownBaseCredentials(authType, 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(BaseCredentials)} does not support writing '{options.Format}' format."); + } + } + + BaseCredentials 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBaseCredentials(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BaseCredentials)} 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 UnknownBaseCredentials FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownBaseCredentials(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/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownBaseCredentials.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownBaseCredentials.cs new file mode 100644 index 000000000000..4bb1fdf662e4 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownBaseCredentials.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.Projects.OneDP +{ + /// Unknown version of BaseCredentials. + internal partial class UnknownBaseCredentials : BaseCredentials + { + /// Initializes a new instance of . + /// The type of credential used by the connection. + /// Keeps track of any properties unknown to the library. + internal UnknownBaseCredentials(CredentialType authType, IDictionary serializedAdditionalRawData) : base(authType, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownBaseCredentials() + { + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownConnection.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownConnection.Serialization.cs new file mode 100644 index 000000000000..79d83fd96682 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownConnection.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.Projects.OneDP +{ + internal partial class UnknownConnection : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Connection)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + Connection 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(Connection)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeConnection(document.RootElement, options); + } + + internal static UnknownConnection DeserializeUnknownConnection(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string authType = "Unknown"; + string name = default; + ConnectionType type = default; + string target = default; + bool isDefault = default; + BaseCredentials credentials = default; + IReadOnlyDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("authType"u8)) + { + authType = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new ConnectionType(property.Value.GetString()); + continue; + } + if (property.NameEquals("target"u8)) + { + target = property.Value.GetString(); + continue; + } + if (property.NameEquals("isDefault"u8)) + { + isDefault = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("credentials"u8)) + { + credentials = BaseCredentials.DeserializeBaseCredentials(property.Value, options); + continue; + } + if (property.NameEquals("metadata"u8)) + { + 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 UnknownConnection( + authType, + name, + type, + target, + isDefault, + credentials, + 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(Connection)} does not support writing '{options.Format}' format."); + } + } + + Connection 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeConnection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Connection)} 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 UnknownConnection FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownConnection(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/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownConnection.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownConnection.cs new file mode 100644 index 000000000000..fffc7cd1d071 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownConnection.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + /// Unknown version of Connection. + internal partial class UnknownConnection : Connection + { + /// Initializes a new instance of . + /// Discriminator property for Connection. + /// The name of the resource. + /// Category of the connection. + /// The connection URL to be used for this service. + /// Whether the connection is tagged as the default connection of its type. + /// + /// The credentials used by the connection + /// 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 . + /// + /// Metadata of the connection. + /// Keeps track of any properties unknown to the library. + internal UnknownConnection(string authType, string name, ConnectionType type, string target, bool isDefault, BaseCredentials credentials, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) : base(authType, name, type, target, isDefault, credentials, metadata, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownConnection() + { + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDatasetVersion.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDatasetVersion.Serialization.cs new file mode 100644 index 000000000000..c2fae38b9fdc --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDatasetVersion.Serialization.cs @@ -0,0 +1,197 @@ +// 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.Projects.OneDP +{ + internal partial class UnknownDatasetVersion : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DatasetVersion)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + DatasetVersion 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(DatasetVersion)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDatasetVersion(document.RootElement, options); + } + + internal static UnknownDatasetVersion DeserializeUnknownDatasetVersion(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string datasetUri = default; + DatasetType type = "Unknown"; + bool? isReference = default; + string stage = default; + string id = default; + string name = default; + string version = default; + string description = default; + IDictionary tags = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("datasetUri"u8)) + { + datasetUri = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new DatasetType(property.Value.GetString()); + continue; + } + if (property.NameEquals("isReference"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + isReference = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stage"u8)) + { + stage = property.Value.GetString(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("version"u8)) + { + version = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("tags"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()); + } + tags = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownDatasetVersion( + datasetUri, + type, + isReference, + stage, + id, + name, + version, + description, + tags ?? 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(DatasetVersion)} does not support writing '{options.Format}' format."); + } + } + + DatasetVersion 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDatasetVersion(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DatasetVersion)} 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 UnknownDatasetVersion FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownDatasetVersion(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/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDatasetVersion.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDatasetVersion.cs new file mode 100644 index 000000000000..d2703979e4a8 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDatasetVersion.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Projects.OneDP +{ + /// Unknown version of DatasetVersion. + internal partial class UnknownDatasetVersion : DatasetVersion + { + /// Initializes a new instance of . + /// [Required] Uri of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + /// Dataset type. + /// Indicates if dataset is reference only or managed by dataset service. If true, the underlying data will be deleted when the dataset version is deleted. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Keeps track of any properties unknown to the library. + internal UnknownDatasetVersion(string datasetUri, DatasetType type, bool? isReference, string stage, string id, string name, string version, string description, IDictionary tags, IDictionary serializedAdditionalRawData) : base(datasetUri, type, isReference, stage, id, name, version, description, tags, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownDatasetVersion() + { + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDeployment.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDeployment.Serialization.cs new file mode 100644 index 000000000000..894a3d9deaa8 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDeployment.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.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + internal partial class UnknownDeployment : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Deployment)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + Deployment 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(Deployment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDeployment(document.RootElement, options); + } + + internal static UnknownDeployment DeserializeUnknownDeployment(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + DeploymentType type = "Unknown"; + string name = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new DeploymentType(property.Value.GetString()); + continue; + } + 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 UnknownDeployment(type, 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(Deployment)} does not support writing '{options.Format}' format."); + } + } + + Deployment 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDeployment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Deployment)} 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 UnknownDeployment FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownDeployment(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/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDeployment.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDeployment.cs new file mode 100644 index 000000000000..4769b1e46cda --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownDeployment.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.Projects.OneDP +{ + /// Unknown version of Deployment. + internal partial class UnknownDeployment : Deployment + { + /// Initializes a new instance of . + /// The type of the deployment. + /// Name of the deployment. + /// Keeps track of any properties unknown to the library. + internal UnknownDeployment(DeploymentType type, string name, IDictionary serializedAdditionalRawData) : base(type, name, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownDeployment() + { + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownIndex.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownIndex.Serialization.cs new file mode 100644 index 000000000000..1181af9e71bf --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownIndex.Serialization.cs @@ -0,0 +1,179 @@ +// 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.Projects.OneDP +{ + internal partial class UnknownIndex : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Index)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + Index 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(Index)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeIndex(document.RootElement, options); + } + + internal static UnknownIndex DeserializeUnknownIndex(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IndexType type = "Unknown"; + string stage = default; + string id = default; + string name = default; + string version = default; + string description = default; + IDictionary tags = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new IndexType(property.Value.GetString()); + continue; + } + if (property.NameEquals("stage"u8)) + { + stage = property.Value.GetString(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("version"u8)) + { + version = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("tags"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()); + } + tags = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownIndex( + type, + stage, + id, + name, + version, + description, + tags ?? 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(Index)} does not support writing '{options.Format}' format."); + } + } + + Index 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeIndex(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Index)} 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 UnknownIndex FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownIndex(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/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownIndex.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownIndex.cs new file mode 100644 index 000000000000..e3f9813a90eb --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownIndex.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.Projects.OneDP +{ + /// Unknown version of Index. + internal partial class UnknownIndex : Index + { + /// Initializes a new instance of . + /// Type of index. + /// Asset stage. + /// A unique identifier for the asset, assetId probably?. + /// The name of the resource. + /// The version of the resource. + /// The asset description text. + /// Tag dictionary. Tags can be added, removed, and updated. + /// Keeps track of any properties unknown to the library. + internal UnknownIndex(IndexType type, string stage, string id, string name, string version, string description, IDictionary tags, IDictionary serializedAdditionalRawData) : base(type, stage, id, name, version, description, tags, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownIndex() + { + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownInputData.Serialization.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownInputData.Serialization.cs new file mode 100644 index 000000000000..2881272fd130 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownInputData.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.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Projects.OneDP +{ + internal partial class UnknownInputData : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InputData)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + InputData 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(InputData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInputData(document.RootElement, options); + } + + internal static UnknownInputData DeserializeUnknownInputData(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 UnknownInputData(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(InputData)} does not support writing '{options.Format}' format."); + } + } + + InputData 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, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeInputData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InputData)} 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 UnknownInputData FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownInputData(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/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownInputData.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownInputData.cs new file mode 100644 index 000000000000..02428d223358 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Generated/UnknownInputData.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.Projects.OneDP +{ + /// Unknown version of InputData. + internal partial class UnknownInputData : InputData + { + /// Initializes a new instance of . + /// Type of the data. + /// Keeps track of any properties unknown to the library. + internal UnknownInputData(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownInputData() + { + } + } +} diff --git a/sdk/ai/Azure.AI.Projects.OneDP/src/Properties/AssemblyInfo.cs b/sdk/ai/Azure.AI.Projects.OneDP/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..e4cec55a9640 --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/src/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Azure.AI.Projects.OneDP.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] + +// Replace Microsoft.Test with the correct resource provider namepace for your service and uncomment. +// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-services-resource-providers +// for the list of possible values. +[assembly: Azure.Core.AzureResourceProviderNamespace("Microsoft.Template")] diff --git a/sdk/ai/Azure.AI.Projects.OneDP/tsp-location.yaml b/sdk/ai/Azure.AI.Projects.OneDP/tsp-location.yaml new file mode 100644 index 000000000000..6628540b60cd --- /dev/null +++ b/sdk/ai/Azure.AI.Projects.OneDP/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/ai/Azure.AI.Projects +commit: b6c1966ad24701cedac1228142f8723d385753e5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/ai/ci.yml b/sdk/ai/ci.yml new file mode 100644 index 000000000000..055fe545a1f2 --- /dev/null +++ b/sdk/ai/ci.yml @@ -0,0 +1,35 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/ai + - sdk/ai/ci.yml + - sdk/ai/Azure.AI.Projects.OneDP + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/ai + - sdk/ai/ci.yml + - sdk/ai/Azure.AI.Projects.OneDP + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: ai + ArtifactName: packages + Artifacts: + - name: Azure.AI.Projects.OneDP + safeName: AzureAIProjectsOneDP