diff --git a/.vscode/cspell.json b/.vscode/cspell.json index 35d5bfbef2f7..d47c8f55ec12 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -1368,6 +1368,18 @@ "updation" // current typo in a swagger ] }, + { + "filename": "sdk/ai/azure-ai-projects/**", + "words": [ + "UPIA", + "ANSII", + "ansii", + "AISEARCH", + "azureai", + "gleu", + "GLEU" + ] + }, { "filename": "sdk/ai/azure-ai-agents-persistent/**", "words": [ diff --git a/eng/versioning/external_dependencies.txt b/eng/versioning/external_dependencies.txt index bfd6690c32ac..c8c602367e32 100644 --- a/eng/versioning/external_dependencies.txt +++ b/eng/versioning/external_dependencies.txt @@ -36,6 +36,8 @@ com.microsoft.azure:qpid-proton-j-extensions;1.2.5 com.microsoft.sqlserver:mssql-jdbc;10.2.3.jre8 com.microsoft.azure:azure-functions-maven-plugin;1.30.0 com.microsoft.azure.functions:azure-functions-java-library;2.2.0 +com.azure:azure-ai-agents-persistent;1.0.0-alpha.20250508.5 +com.azure:azure-ai-inference;1.0.0-beta.4 com.mysql:mysql-connector-j;9.0.0 com.openai:openai-java;1.3.1 com.squareup.okhttp3:okhttp;4.12.0 diff --git a/eng/versioning/version_client.txt b/eng/versioning/version_client.txt index 0336d298afae..b2dedf940101 100644 --- a/eng/versioning/version_client.txt +++ b/eng/versioning/version_client.txt @@ -50,6 +50,7 @@ com.azure:azure-ai-openai-assistants;1.0.0-beta.5;1.0.0-beta.6 com.azure:azure-ai-openai-realtime;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-ai-openai-stainless;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-ai-personalizer;1.0.0-beta.1;1.0.0-beta.2 +com.azure:azure-ai-projects;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-ai-textanalytics;5.5.6;5.6.0-beta.1 com.azure:azure-ai-textanalytics-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-ai-translation-text;1.1.2;1.2.0-beta.1 diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md new file mode 100644 index 000000000000..cc87dea383af --- /dev/null +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -0,0 +1,13 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +- Azure Projects client library for Java. This package contains Microsoft Azure Projects client library. + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes diff --git a/sdk/ai/azure-ai-projects/README.md b/sdk/ai/azure-ai-projects/README.md new file mode 100644 index 000000000000..6a8d3521adad --- /dev/null +++ b/sdk/ai/azure-ai-projects/README.md @@ -0,0 +1,78 @@ +# Azure Projects client library for Java + +Azure Projects client library for Java. + +This package contains Microsoft Azure Projects client library. + +## Documentation + +Various documentation is available to help you get started + +- [API reference documentation][docs] +- [Product documentation][product_documentation] + +## Getting started + +### Prerequisites + +- [Java Development Kit (JDK)][jdk] with version 8 or above +- [Azure Subscription][azure_subscription] + +### Adding the package to your product + +[//]: # ({x-version-update-start;com.azure:azure-ai-projects;current}) +```xml + + com.azure + azure-ai-projects + 1.0.0-beta.1 + +``` +[//]: # ({x-version-update-end}) + +### Authentication + +[Azure Identity][azure_identity] package provides the default implementation for authenticating the client. + +## Key concepts + +## Examples + +```java com.azure.ai.projects.readme +``` + +### Service API versions + +The client library targets the latest service API version by default. +The service client builder accepts an optional service API version parameter to specify which API version to communicate. + +#### Select a service API version + +You have the flexibility to explicitly select a supported service API version when initializing a service client via the service client builder. +This ensures that the client can communicate with services using the specified API version. + +When selecting an API version, it is 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. + +## Troubleshooting + +## Next steps + +## Contributing + +For details on contributing to this repository, see the [contributing guide](https://github.com/Azure/azure-sdk-for-java/blob/main/CONTRIBUTING.md). + +1. Fork it +1. Create your feature branch (`git checkout -b my-new-feature`) +1. Commit your changes (`git commit -am 'Add some feature'`) +1. Push to the branch (`git push origin my-new-feature`) +1. Create new Pull Request + + +[product_documentation]: https://azure.microsoft.com/services/ +[docs]: https://azure.github.io/azure-sdk-for-java/ +[jdk]: https://learn.microsoft.com/azure/developer/java/fundamentals/ +[azure_subscription]: https://azure.microsoft.com/free/ +[azure_identity]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity diff --git a/sdk/ai/azure-ai-projects/assets.json b/sdk/ai/azure-ai-projects/assets.json new file mode 100644 index 000000000000..5f7bb13ffd62 --- /dev/null +++ b/sdk/ai/azure-ai-projects/assets.json @@ -0,0 +1 @@ +{"AssetsRepo":"Azure/azure-sdk-assets","AssetsRepoPrefixPath":"java","TagPrefix":"java/ai/azure-ai-projects","Tag": "java/ai/azure-ai-projects_de0a038f6e"} \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/pom.xml b/sdk/ai/azure-ai-projects/pom.xml new file mode 100644 index 000000000000..44087522e2d6 --- /dev/null +++ b/sdk/ai/azure-ai-projects/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + com.azure + azure-client-sdk-parent + 1.7.0 + ../../parents/azure-client-sdk-parent + + + com.azure + azure-ai-projects + 1.0.0-beta.1 + jar + + Microsoft Azure SDK for Projects + This package contains Microsoft Azure Projects client library. + https://github.com/Azure/azure-sdk-for-java + + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + + https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + + microsoft + Microsoft + + + + UTF-8 + + 0.15 + 0.10 + + + --add-exports com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED + --add-opens com.azure.core/com.azure.core.implementation.util=ALL-UNNAMED + + + + + com.azure + azure-core + 1.55.3 + + + com.azure + azure-core-http-netty + 1.15.11 + + + com.azure + azure-storage-blob + 12.30.0 + + + com.azure + azure-ai-agents-persistent + 1.0.0-alpha.20250508.5 + + + com.azure + azure-ai-inference + 1.0.0-beta.4 + + + + + + com.azure + azure-core-test + 1.27.0-beta.8 + test + + + com.azure + azure-identity + 1.16.0 + test + + + + + + azure-sdk-for-java + https://pkgs.dev.azure.com/azure-sdk/public/_packaging/azure-sdk-for-java/maven/v1 + + true + + + true + + + + diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/AIProjectClientBuilder.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/AIProjectClientBuilder.java new file mode 100644 index 000000000000..252470cb31c0 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/AIProjectClientBuilder.java @@ -0,0 +1,466 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.AIProjectClientImpl; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.client.traits.ConfigurationTrait; +import com.azure.core.client.traits.EndpointTrait; +import com.azure.core.client.traits.HttpTrait; +import com.azure.core.client.traits.TokenCredentialTrait; +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.AddHeadersPolicy; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.HttpLoggingPolicy; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.core.http.policy.HttpPolicyProviders; +import com.azure.core.http.policy.RequestIdPolicy; +import com.azure.core.http.policy.RetryOptions; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.util.ClientOptions; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.builder.ClientBuilderUtil; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.serializer.JacksonAdapter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * A builder for creating a new instance of the AIProjectClient type. + */ +@ServiceClientBuilder( + serviceClients = { + ConnectionsClient.class, + EvaluationsClient.class, + DatasetsClient.class, + IndexesClient.class, + DeploymentsClient.class, + RedTeamsClient.class, + ConnectionsAsyncClient.class, + EvaluationsAsyncClient.class, + DatasetsAsyncClient.class, + IndexesAsyncClient.class, + DeploymentsAsyncClient.class, + RedTeamsAsyncClient.class }) +public final class AIProjectClientBuilder + implements HttpTrait, ConfigurationTrait, + TokenCredentialTrait, EndpointTrait { + + @Generated + private static final String SDK_NAME = "name"; + + @Generated + private static final String SDK_VERSION = "version"; + + @Generated + private static final String[] DEFAULT_SCOPES = new String[] { "https://ai.azure.com/.default" }; + + @Generated + private static final Map PROPERTIES = CoreUtils.getProperties("azure-ai-projects.properties"); + + @Generated + private final List pipelinePolicies; + + /** + * Create an instance of the AIProjectClientBuilder. + */ + @Generated + public AIProjectClientBuilder() { + this.pipelinePolicies = new ArrayList<>(); + } + + /* + * The HTTP pipeline to send requests through. + */ + @Generated + private HttpPipeline pipeline; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public AIProjectClientBuilder pipeline(HttpPipeline pipeline) { + if (this.pipeline != null && pipeline == null) { + LOGGER.atInfo().log("HttpPipeline is being set to 'null' when it was previously configured."); + } + this.pipeline = pipeline; + return this; + } + + /* + * The HTTP client used to send the request. + */ + @Generated + private HttpClient httpClient; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public AIProjectClientBuilder httpClient(HttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /* + * The logging configuration for HTTP requests and responses. + */ + @Generated + private HttpLogOptions httpLogOptions; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public AIProjectClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) { + this.httpLogOptions = httpLogOptions; + return this; + } + + /* + * The client options such as application ID and custom headers to set on a request. + */ + @Generated + private ClientOptions clientOptions; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public AIProjectClientBuilder clientOptions(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + return this; + } + + /* + * The retry options to configure retry policy for failed requests. + */ + @Generated + private RetryOptions retryOptions; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public AIProjectClientBuilder retryOptions(RetryOptions retryOptions) { + this.retryOptions = retryOptions; + return this; + } + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public AIProjectClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { + Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); + pipelinePolicies.add(customPolicy); + return this; + } + + /* + * The configuration store that is used during construction of the service client. + */ + @Generated + private Configuration configuration; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public AIProjectClientBuilder configuration(Configuration configuration) { + this.configuration = configuration; + return this; + } + + /* + * The TokenCredential used for authentication. + */ + @Generated + private TokenCredential tokenCredential; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public AIProjectClientBuilder credential(TokenCredential tokenCredential) { + this.tokenCredential = tokenCredential; + return this; + } + + /* + * The service endpoint + */ + @Generated + private String endpoint; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public AIProjectClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /* + * Service version + */ + @Generated + private ProjectsServiceVersion serviceVersion; + + /** + * Sets Service version. + * + * @param serviceVersion the serviceVersion value. + * @return the AIProjectClientBuilder. + */ + @Generated + public AIProjectClientBuilder serviceVersion(ProjectsServiceVersion serviceVersion) { + this.serviceVersion = serviceVersion; + return this; + } + + /* + * The retry policy that will attempt to retry failed requests, if applicable. + */ + @Generated + private RetryPolicy retryPolicy; + + /** + * Sets The retry policy that will attempt to retry failed requests, if applicable. + * + * @param retryPolicy the retryPolicy value. + * @return the AIProjectClientBuilder. + */ + @Generated + public AIProjectClientBuilder retryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; + return this; + } + + /** + * Builds an instance of AIProjectClientImpl with the provided parameters. + * + * @return an instance of AIProjectClientImpl. + */ + @Generated + private AIProjectClientImpl buildInnerClient() { + this.validateClient(); + HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); + ProjectsServiceVersion localServiceVersion + = (serviceVersion != null) ? serviceVersion : ProjectsServiceVersion.getLatest(); + AIProjectClientImpl client = new AIProjectClientImpl(localPipeline, + JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); + return client; + } + + @Generated + private void validateClient() { + // This method is invoked from 'buildInnerClient'/'buildClient' method. + // Developer can customize this method, to validate that the necessary conditions are met for the new client. + Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); + } + + @Generated + private HttpPipeline createHttpPipeline() { + Configuration buildConfiguration + = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; + HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; + ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; + List policies = new ArrayList<>(); + String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); + policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); + policies.add(new RequestIdPolicy()); + policies.add(new AddHeadersFromContextPolicy()); + HttpHeaders headers = CoreUtils.createHttpHeadersFromClientOptions(localClientOptions); + if (headers != null) { + policies.add(new AddHeadersPolicy(headers)); + } + this.pipelinePolicies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) + .forEach(p -> policies.add(p)); + HttpPolicyProviders.addBeforeRetryPolicies(policies); + policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); + policies.add(new AddDatePolicy()); + if (tokenCredential != null) { + policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPES)); + } + this.pipelinePolicies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) + .forEach(p -> policies.add(p)); + HttpPolicyProviders.addAfterRetryPolicies(policies); + policies.add(new HttpLoggingPolicy(localHttpLogOptions)); + HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) + .httpClient(httpClient) + .clientOptions(localClientOptions) + .build(); + return httpPipeline; + } + + /** + * Builds an instance of ConnectionsAsyncClient class. + * + * @return an instance of ConnectionsAsyncClient. + */ + @Generated + public ConnectionsAsyncClient buildConnectionsAsyncClient() { + return new ConnectionsAsyncClient(buildInnerClient().getConnections()); + } + + /** + * Builds an instance of EvaluationsAsyncClient class. + * + * @return an instance of EvaluationsAsyncClient. + */ + @Generated + public EvaluationsAsyncClient buildEvaluationsAsyncClient() { + return new EvaluationsAsyncClient(buildInnerClient().getEvaluations()); + } + + /** + * Builds an instance of DatasetsAsyncClient class. + * + * @return an instance of DatasetsAsyncClient. + */ + @Generated + public DatasetsAsyncClient buildDatasetsAsyncClient() { + return new DatasetsAsyncClient(buildInnerClient().getDatasets()); + } + + /** + * Builds an instance of IndexesAsyncClient class. + * + * @return an instance of IndexesAsyncClient. + */ + @Generated + public IndexesAsyncClient buildIndexesAsyncClient() { + return new IndexesAsyncClient(buildInnerClient().getIndexes()); + } + + /** + * Builds an instance of DeploymentsAsyncClient class. + * + * @return an instance of DeploymentsAsyncClient. + */ + @Generated + public DeploymentsAsyncClient buildDeploymentsAsyncClient() { + return new DeploymentsAsyncClient(buildInnerClient().getDeployments()); + } + + /** + * Builds an instance of RedTeamsAsyncClient class. + * + * @return an instance of RedTeamsAsyncClient. + */ + @Generated + public RedTeamsAsyncClient buildRedTeamsAsyncClient() { + return new RedTeamsAsyncClient(buildInnerClient().getRedTeams()); + } + + /** + * Builds an instance of ConnectionsClient class. + * + * @return an instance of ConnectionsClient. + */ + @Generated + public ConnectionsClient buildConnectionsClient() { + return new ConnectionsClient(buildInnerClient().getConnections()); + } + + /** + * Builds an instance of EvaluationsClient class. + * + * @return an instance of EvaluationsClient. + */ + @Generated + public EvaluationsClient buildEvaluationsClient() { + return new EvaluationsClient(buildInnerClient().getEvaluations()); + } + + /** + * Builds an instance of DatasetsClient class. + * + * @return an instance of DatasetsClient. + */ + @Generated + public DatasetsClient buildDatasetsClient() { + return new DatasetsClient(buildInnerClient().getDatasets()); + } + + /** + * Builds an instance of IndexesClient class. + * + * @return an instance of IndexesClient. + */ + @Generated + public IndexesClient buildIndexesClient() { + return new IndexesClient(buildInnerClient().getIndexes()); + } + + /** + * Builds an instance of DeploymentsClient class. + * + * @return an instance of DeploymentsClient. + */ + @Generated + public DeploymentsClient buildDeploymentsClient() { + return new DeploymentsClient(buildInnerClient().getDeployments()); + } + + /** + * Builds an instance of RedTeamsClient class. + * + * @return an instance of RedTeamsClient. + */ + @Generated + public RedTeamsClient buildRedTeamsClient() { + return new RedTeamsClient(buildInnerClient().getRedTeams()); + } + + /** + * Builds an instance of TelemetryClient + * + * @return an instance of TelemetryClient. + */ + public TelemetryClient buildTelemetryClient() { + ConnectionsClient connectionsClient = this.buildConnectionsClient(); + return new TelemetryClient(connectionsClient); + } + + /** + * Builds an instance of TelemetryAsyncClient + * + * @return an instance of TelemetryAsyncClient. + */ + public TelemetryAsyncClient buildTelemetryAsyncClient() { + ConnectionsAsyncClient connectionsAsyncClient = this.buildConnectionsAsyncClient(); + return new TelemetryAsyncClient(connectionsAsyncClient); + } + + private static final ClientLogger LOGGER = new ClientLogger(AIProjectClientBuilder.class); +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/ConnectionsAsyncClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/ConnectionsAsyncClient.java new file mode 100644 index 000000000000..7c4d6b19c03f --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/ConnectionsAsyncClient.java @@ -0,0 +1,341 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.ConnectionsImpl; +import com.azure.ai.projects.models.Connection; +import com.azure.ai.projects.models.ConnectionType; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import java.util.stream.Collectors; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class, isAsync = true) +public final class ConnectionsAsyncClient { + + @Generated + private final ConnectionsImpl serviceClient; + + /** + * Initializes an instance of ConnectionsAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + ConnectionsAsyncClient(ConnectionsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Get a connection by name, with or without its connection credentials. + * + * @param name The friendly name of the connection, provided by the user. + * @param includeCredentials Whether to include connection credentials in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connection by name, with or without its connection credentials on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getConnection(String name, boolean includeCredentials) { + if (includeCredentials) { + return getConnectionWithCredentials(name); + } else { + return getConnection(name); + } + } + + /** + * Get the default connection for a given connection type. + * + * @param connectionType The type of the connection + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return Default connection of the type specified on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getDefaultConnection(ConnectionType connectionType) { + return getDefaultConnection(connectionType, false); + } + + /** + * Get the default connection for a given connection type. + * + * @param connectionType The type of the connection + * @param includeCredentials Whether to include connection credentials in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return Default connection of the type specified on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getDefaultConnection(ConnectionType connectionType, boolean includeCredentials) { + return listConnections(connectionType, true).filter(Connection::isDefault).next().flatMap(connection -> { + if (includeCredentials && connection != null) { + return getConnectionWithCredentials(connection.getName()); + } else { + return Mono.just(connection); + } + }); + } + + /** + * List all connections in the project, without populating connection credentials. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
connectionTypeStringNoList connections of this specific type. Allowed values: + * "AzureOpenAI", "AzureBlob", "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", "AppConfig", + * "AppInsights", "CustomKeys".
defaultConnectionBooleanNoList connections that are default + * connections
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Connection items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listConnections(RequestOptions requestOptions) { + return this.serviceClient.listConnectionsAsync(requestOptions); + } + + /** + * List all connections in the project, without populating connection credentials. + * + * @param connectionType List connections of this specific type. + * @param defaultConnection List connections that are default connections. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Connection items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listConnections(ConnectionType connectionType, Boolean defaultConnection) { + // Generated convenience method for listConnections + RequestOptions requestOptions = new RequestOptions(); + if (connectionType != null) { + requestOptions.addQueryParam("connectionType", connectionType.toString(), false); + } + if (defaultConnection != null) { + requestOptions.addQueryParam("defaultConnection", String.valueOf(defaultConnection), false); + } + PagedFlux pagedFluxResponse = listConnections(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(Connection.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * List all connections in the project, without populating connection credentials. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Connection items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listConnections() { + // Generated convenience method for listConnections + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listConnections(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(Connection.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * Get a connection by name, without populating connection credentials. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The friendly name of the connection, provided by the user. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a connection by name, without populating connection credentials along with {@link Response} on successful + * completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono> getConnectionWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getConnectionWithResponseAsync(name, requestOptions); + } + + /** + * Get a connection by name, without populating connection credentials. + * + * @param name The friendly name of the connection, provided by the user. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connection by name, without populating connection credentials on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono getConnection(String name) { + // Generated convenience method for getConnectionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getConnectionWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(Connection.class)); + } + + /** + * Get a connection by name, with its connection credentials. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The friendly name of the connection, provided by the user. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a connection by name, with its connection credentials along with {@link Response} on successful + * completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono> getConnectionWithCredentialsWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getConnectionWithCredentialsWithResponseAsync(name, requestOptions); + } + + /** + * Get a connection by name, with its connection credentials. + * + * @param name The friendly name of the connection, provided by the user. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connection by name, with its connection credentials on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono getConnectionWithCredentials(String name) { + // Generated convenience method for getConnectionWithCredentialsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getConnectionWithCredentialsWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(Connection.class)); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/ConnectionsClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/ConnectionsClient.java new file mode 100644 index 000000000000..f9521ba1d1cb --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/ConnectionsClient.java @@ -0,0 +1,308 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.ConnectionsImpl; +import com.azure.ai.projects.models.Connection; +import com.azure.ai.projects.models.ConnectionType; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; + +/** + * Initializes a new instance of the synchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class) +public final class ConnectionsClient { + + @Generated + private final ConnectionsImpl serviceClient; + + /** + * Initializes an instance of ConnectionsClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + ConnectionsClient(ConnectionsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Get the default connection for a given connection type. + * + * @param connectionType The type of the connection + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return Default connection of the type specified. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Connection getDefaultConnection(ConnectionType connectionType) { + return this.getDefaultConnection(connectionType, false); + } + + /** + * Get the default connection for a given connection type. + * + * @param connectionType The type of the connection + * @param includeCredentials Whether to include connection credentials in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return Default connection of the type specified. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Connection getDefaultConnection(ConnectionType connectionType, boolean includeCredentials) { + PagedIterable connections = this.listConnections(connectionType, true); + for (Connection connection : connections) { + if (connection.isDefault()) { + return connection; + } + } + return null; + } + + /** + * List all connections in the project, without populating connection credentials. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
connectionTypeStringNoList connections of this specific type. Allowed values: + * "AzureOpenAI", "AzureBlob", "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", "AppConfig", + * "AppInsights", "CustomKeys".
defaultConnectionBooleanNoList connections that are default + * connections
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Connection items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listConnections(RequestOptions requestOptions) { + return this.serviceClient.listConnections(requestOptions); + } + + /** + * List all connections in the project, without populating connection credentials. + * + * @param connectionType List connections of this specific type. + * @param defaultConnection List connections that are default connections. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Connection items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listConnections(ConnectionType connectionType, Boolean defaultConnection) { + // Generated convenience method for listConnections + RequestOptions requestOptions = new RequestOptions(); + if (connectionType != null) { + requestOptions.addQueryParam("connectionType", connectionType.toString(), false); + } + if (defaultConnection != null) { + requestOptions.addQueryParam("defaultConnection", String.valueOf(defaultConnection), false); + } + return serviceClient.listConnections(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(Connection.class)); + } + + /** + * List all connections in the project, without populating connection credentials. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Connection items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listConnections() { + // Generated convenience method for listConnections + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listConnections(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(Connection.class)); + } + + /** + * Get a connection by name, without populating connection credentials. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The friendly name of the connection, provided by the user. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a connection by name, without populating connection credentials along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Response getConnectionWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getConnectionWithResponse(name, requestOptions); + } + + /** + * Get a connection by name, with its connection credentials. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The friendly name of the connection, provided by the user. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a connection by name, with its connection credentials along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Response getConnectionWithCredentialsWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getConnectionWithCredentialsWithResponse(name, requestOptions); + } + + /** + * Get a connection by name, with its connection credentials. + * + * @param name The friendly name of the connection, provided by the user. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connection by name, with its connection credentials. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Connection getConnectionWithCredentials(String name) { + // Generated convenience method for getConnectionWithCredentialsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getConnectionWithCredentialsWithResponse(name, requestOptions).getValue().toObject(Connection.class); + } + + /** + * Get a connection by name, without populating connection credentials. + * + * @param name The friendly name of the connection, provided by the user. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connection by name, without populating connection credentials. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Connection getConnection(String name) { + // Generated convenience method for getConnectionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getConnectionWithResponse(name, requestOptions).getValue().toObject(Connection.class); + } + + /** + * Get a connection by name, without populating connection credentials. + * + * @param name The friendly name of the connection, provided by the user. + * @param includeCredentials Whether to include connection credentials in the response. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a connection by name, without populating connection credentials. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Connection getConnection(String name, boolean includeCredentials) { + if (includeCredentials) { + return getConnectionWithCredentials(name); + } else { + return getConnection(name); + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DatasetsAsyncClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DatasetsAsyncClient.java new file mode 100644 index 000000000000..75cc821376cb --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DatasetsAsyncClient.java @@ -0,0 +1,595 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.DatasetsImpl; +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.ai.projects.models.AssetCredentialResult; +import com.azure.ai.projects.models.DatasetVersion; +import com.azure.ai.projects.models.FileDatasetVersion; +import com.azure.ai.projects.models.FolderDatasetVersion; +import com.azure.ai.projects.models.PendingUploadRequest; +import com.azure.ai.projects.models.PendingUploadResponse; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.logging.ClientLogger; +import com.azure.storage.blob.BlobAsyncClient; +import com.azure.storage.blob.BlobClientBuilder; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Collectors; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class, isAsync = true) +public final class DatasetsAsyncClient { + + @Generated + private final DatasetsImpl serviceClient; + + private final ClientLogger logger = new ClientLogger(DatasetsAsyncClient.class); + + /** + * Initializes an instance of DatasetsAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + DatasetsAsyncClient(DatasetsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Start a new or get an existing pending upload of a dataset for a specific version. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     pendingUploadId: String (Optional)
+     *     connectionName: String (Optional)
+     *     pendingUploadType: String(None/BlobReference) (Required)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     blobReference (Required): {
+     *         blobUri: String (Required)
+     *         storageAccountArmId: String (Required)
+     *         credential (Required): {
+     *             sasUri: String (Required)
+     *             type: String (Required)
+     *         }
+     *     }
+     *     pendingUploadId: String (Required)
+     *     version: String (Optional)
+     *     pendingUploadType: String(None/BlobReference) (Required)
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @param body Parameters for the action. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents the response for a pending upload request along with {@link Response} on successful completion + * of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> pendingUploadWithResponse(String name, String version, BinaryData body, + RequestOptions requestOptions) { + return this.serviceClient.pendingUploadWithResponseAsync(name, version, body, requestOptions); + } + + /** + * Get the SAS credential to access the storage account associated with a Dataset version. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     blobReference (Required): {
+     *         blobUri: String (Required)
+     *         storageAccountArmId: String (Required)
+     *         credential (Required): {
+     *             sasUri: String (Required)
+     *             type: String (Required)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the SAS credential to access the storage account associated with a Dataset version along with + * {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getCredentialsWithResponse(String name, String version, + RequestOptions requestOptions) { + return this.serviceClient.getCredentialsWithResponseAsync(name, version, requestOptions); + } + + /** + * Start a new or get an existing pending upload of a dataset for a specific version. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @param body Parameters for the action. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents the response for a pending upload request on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono pendingUpload(String name, String version, PendingUploadRequest body) { + // Generated convenience method for pendingUploadWithResponse + RequestOptions requestOptions = new RequestOptions(); + return pendingUploadWithResponse(name, version, BinaryData.fromObject(body), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(PendingUploadResponse.class)); + } + + /** + * Get the SAS credential to access the storage account associated with a Dataset version. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the SAS credential to access the storage account associated with a Dataset version on successful + * completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getCredentials(String name, String version) { + // Generated convenience method for getCredentialsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getCredentialsWithResponse(name, version, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(AssetCredentialResult.class)); + } + + /** + * Creates a dataset from a file. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to create or replace. + * @param filePath The path to the file to upload. + * @return A Mono that completes with a FileDatasetVersion representing the created dataset. + * @throws IllegalArgumentException If the provided path is not a file + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createDatasetWithFile(String name, String version, Path filePath) { + if (!Files.isRegularFile(filePath)) { + return Mono.error(new IllegalArgumentException("The provided path is not a file: " + filePath)); + } + PendingUploadRequest request = new PendingUploadRequest(); + return this.pendingUpload(name, version, request).flatMap(pendingUploadResponse -> { + String blobUri = pendingUploadResponse.getBlobReference().getBlobUri(); + String sasUri = pendingUploadResponse.getBlobReference().getCredential().getSasUri(); + BlobAsyncClient blobClient = new BlobClientBuilder().endpoint(sasUri).blobName(name).buildAsyncClient(); + return blobClient.upload(BinaryData.fromFile(filePath), true).thenReturn(blobClient.getBlobUrl()); + }).flatMap(blobUrl -> { + RequestOptions requestOptions = new RequestOptions(); + FileDatasetVersion fileDataset = new FileDatasetVersion().setDataUri(blobUrl); + return this + .createOrUpdateDatasetVersionWithResponse(name, version, BinaryData.fromObject(fileDataset), + requestOptions) + .flatMap(FluxUtil::toMono) + .map(data -> data.toObject(FileDatasetVersion.class)); + }); + } + + /** + * Creates a dataset from a folder. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to create or replace. + * @param folderPath The path to the folder containing files to upload. + * @return A Mono that completes with a FolderDatasetVersion representing the created dataset. + * @throws IllegalArgumentException If the provided path is not a directory. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createDatasetWithFolder(String name, String version, Path folderPath) { + if (!Files.isDirectory(folderPath)) { + return Mono.error(new IllegalArgumentException("The provided path is not a folder: " + folderPath)); + } + // Request a pending upload for the folder + PendingUploadRequest request = new PendingUploadRequest(); + return this.pendingUpload(name, version, request).flatMap(pendingUploadResponse -> { + String blobContainerUri = pendingUploadResponse.getBlobReference().getBlobUri(); + String sasUri = pendingUploadResponse.getBlobReference().getCredential().getSasUri(); + String containerUrl = blobContainerUri.substring(0, blobContainerUri.lastIndexOf('/')); + // Find all files in the directory + try { + List files = Files.walk(folderPath).filter(Files::isRegularFile).collect(Collectors.toList()); + // Upload each file in the directory one after another + return Flux.fromIterable(files).flatMap(filePath -> { + // Calculate relative path from the base folder + String relativePath = folderPath.relativize(filePath).toString().replace('\\', '/'); + // Create blob client for each file + BlobAsyncClient blobClient + = new BlobClientBuilder().endpoint(sasUri).blobName(relativePath).buildAsyncClient(); + // Upload the file + return blobClient.upload(BinaryData.fromFile(filePath), true); + }).then(Mono.just(containerUrl)); + } catch (Exception e) { + return Mono.error(new RuntimeException("Error walking through folder path", e)); + } + }).flatMap(containerUrl -> { + // Create a FolderDatasetVersion with the container URL + RequestOptions requestOptions = new RequestOptions(); + FolderDatasetVersion folderDataset = new FolderDatasetVersion().setDataUri(containerUrl); + return this + .createOrUpdateDatasetVersionWithResponse(name, version, BinaryData.fromObject(folderDataset), + requestOptions) + .flatMap(FluxUtil::toMono) + .map(data -> data.toObject(FolderDatasetVersion.class)); + }); + } + + /** + * List all versions of the given DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listDatasetVersions(String name, RequestOptions requestOptions) { + return this.serviceClient.listDatasetVersionsAsync(name, requestOptions); + } + + /** + * List the latest version of each DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listLatestDatasetVersions(RequestOptions requestOptions) { + return this.serviceClient.listLatestDatasetVersionsAsync(requestOptions); + } + + /** + * Get the specific version of the DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to retrieve. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the specific version of the DatasetVersion along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getDatasetVersionWithResponse(String name, String version, + RequestOptions requestOptions) { + return this.serviceClient.getDatasetVersionWithResponseAsync(name, version, requestOptions); + } + + /** + * Delete the specific version of the DatasetVersion. + * + * @param name The name of the resource. + * @param version The version of the DatasetVersion to delete. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteDatasetVersionWithResponse(String name, String version, + RequestOptions requestOptions) { + return this.serviceClient.deleteDatasetVersionWithResponseAsync(name, version, requestOptions); + } + + /** + * Create a new or update an existing DatasetVersion with the given version id. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to create or replace. + * @param body The definition of the DatasetVersion to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return datasetVersion Definition along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateDatasetVersionWithResponse(String name, String version, + BinaryData body, RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateDatasetVersionWithResponseAsync(name, version, body, requestOptions); + } + + /** + * List all versions of the given DatasetVersion. + * + * @param name The name of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listDatasetVersions(String name) { + // Generated convenience method for listDatasetVersions + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listDatasetVersions(name, requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(DatasetVersion.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * List the latest version of each DatasetVersion. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listLatestDatasetVersions() { + // Generated convenience method for listLatestDatasetVersions + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listLatestDatasetVersions(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(DatasetVersion.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * Get the specific version of the DatasetVersion. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to retrieve. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specific version of the DatasetVersion on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getDatasetVersion(String name, String version) { + // Generated convenience method for getDatasetVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDatasetVersionWithResponse(name, version, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(DatasetVersion.class)); + } + + /** + * Delete the specific version of the DatasetVersion. + * + * @param name The name of the resource. + * @param version The version of the DatasetVersion to delete. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono deleteDatasetVersion(String name, String version) { + // Generated convenience method for deleteDatasetVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteDatasetVersionWithResponse(name, version, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Create a new or update an existing DatasetVersion with the given version id. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to create or replace. + * @param body The definition of the DatasetVersion to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return datasetVersion Definition on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdateDatasetVersion(String name, String version, DatasetVersion body) { + // Generated convenience method for createOrUpdateDatasetVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + JsonMergePatchHelper.getDatasetVersionAccessor().prepareModelForJsonMergePatch(body, true); + BinaryData bodyInBinaryData = BinaryData.fromObject(body); + // BinaryData.fromObject() will not fire serialization, use getLength() to fire serialization. + bodyInBinaryData.getLength(); + JsonMergePatchHelper.getDatasetVersionAccessor().prepareModelForJsonMergePatch(body, false); + return createOrUpdateDatasetVersionWithResponse(name, version, bodyInBinaryData, requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(DatasetVersion.class)); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DatasetsClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DatasetsClient.java new file mode 100644 index 000000000000..a4bced86d7ba --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DatasetsClient.java @@ -0,0 +1,553 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.DatasetsImpl; +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.ai.projects.models.AssetCredentialResult; +import com.azure.ai.projects.models.DatasetVersion; +import com.azure.ai.projects.models.FileDatasetVersion; +import com.azure.ai.projects.models.FolderDatasetVersion; +import com.azure.ai.projects.models.PendingUploadRequest; +import com.azure.ai.projects.models.PendingUploadResponse; +import com.azure.ai.projects.models.SasCredential; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.logging.ClientLogger; +import com.azure.storage.blob.BlobClient; +import com.azure.storage.blob.BlobClientBuilder; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Initializes a new instance of the synchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class) +public final class DatasetsClient { + + private final ClientLogger logger = new ClientLogger(DatasetsClient.class); + + @Generated + private final DatasetsImpl serviceClient; + + /** + * Initializes an instance of DatasetsClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + DatasetsClient(DatasetsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Start a new or get an existing pending upload of a dataset for a specific version. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     pendingUploadId: String (Optional)
+     *     connectionName: String (Optional)
+     *     pendingUploadType: String(None/BlobReference) (Required)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     blobReference (Required): {
+     *         blobUri: String (Required)
+     *         storageAccountArmId: String (Required)
+     *         credential (Required): {
+     *             sasUri: String (Required)
+     *             type: String (Required)
+     *         }
+     *     }
+     *     pendingUploadId: String (Required)
+     *     version: String (Optional)
+     *     pendingUploadType: String(None/BlobReference) (Required)
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @param body Parameters for the action. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents the response for a pending upload request along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response pendingUploadWithResponse(String name, String version, BinaryData body, + RequestOptions requestOptions) { + return this.serviceClient.pendingUploadWithResponse(name, version, body, requestOptions); + } + + /** + * Get the SAS credential to access the storage account associated with a Dataset version. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     blobReference (Required): {
+     *         blobUri: String (Required)
+     *         storageAccountArmId: String (Required)
+     *         credential (Required): {
+     *             sasUri: String (Required)
+     *             type: String (Required)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the SAS credential to access the storage account associated with a Dataset version along with + * {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getCredentialsWithResponse(String name, String version, RequestOptions requestOptions) { + return this.serviceClient.getCredentialsWithResponse(name, version, requestOptions); + } + + /** + * Start a new or get an existing pending upload of a dataset for a specific version. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @param body Parameters for the action. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return represents the response for a pending upload request. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public PendingUploadResponse pendingUpload(String name, String version, PendingUploadRequest body) { + // Generated convenience method for pendingUploadWithResponse + RequestOptions requestOptions = new RequestOptions(); + return pendingUploadWithResponse(name, version, BinaryData.fromObject(body), requestOptions).getValue() + .toObject(PendingUploadResponse.class); + } + + /** + * Get the SAS credential to access the storage account associated with a Dataset version. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the SAS credential to access the storage account associated with a Dataset version. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public AssetCredentialResult getCredentials(String name, String version) { + // Generated convenience method for getCredentialsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getCredentialsWithResponse(name, version, requestOptions).getValue() + .toObject(AssetCredentialResult.class); + } + + /** + * Creates a dataset from a folder. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to create or replace. + * @param filePath The path to the folder containing files to upload. + * @return A FileDatasetVersion representing the created dataset. + * @throws IllegalArgumentException If the provided path is not a file + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public FileDatasetVersion createDatasetWithFile(String name, String version, Path filePath) { + if (!Files.isRegularFile(filePath)) { + throw logger + .logExceptionAsError(new IllegalArgumentException("The provided path is not a file: " + filePath)); + } + PendingUploadRequest body = new PendingUploadRequest(); + PendingUploadResponse pendingUploadResponse = this.pendingUpload(name, version, body); + SasCredential credential = pendingUploadResponse.getBlobReference().getCredential(); + String blobUri = pendingUploadResponse.getBlobReference().getBlobUri(); + BlobClient blobClient = new BlobClientBuilder().endpoint(credential.getSasUri()).blobName(name).buildClient(); + blobClient.upload(BinaryData.fromFile(filePath)); + RequestOptions requestOptions = new RequestOptions(); + FileDatasetVersion datasetVersion = this + .createOrUpdateDatasetVersionWithResponse(name, version, + BinaryData.fromObject(new FileDatasetVersion().setDataUri(blobClient.getBlobUrl())), requestOptions) + .getValue() + .toObject(FileDatasetVersion.class); + return datasetVersion; + } + + /** + * Creates a dataset from a folder. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to create or replace. + * @param folderPath The path to the folder containing files to upload. + * @return A FolderDatasetVersion representing the created dataset. + * @throws IllegalArgumentException If the provided path is not a directory. + * @throws IOException if an I/ O error is thrown when accessing the starting file + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public FolderDatasetVersion createDatasetWithFolder(String name, String version, Path folderPath) + throws IOException { + if (!Files.isDirectory(folderPath)) { + throw logger + .logExceptionAsError(new IllegalArgumentException("The provided path is not a folder: " + folderPath)); + } + // Request a pending upload for the folder + PendingUploadRequest request = new PendingUploadRequest(); + PendingUploadResponse pendingUploadResponse = this.pendingUpload(name, version, request); + String blobContainerUri = pendingUploadResponse.getBlobReference().getBlobUri(); + SasCredential credential = pendingUploadResponse.getBlobReference().getCredential(); + String containerUrl = blobContainerUri.substring(0, blobContainerUri.lastIndexOf('/')); + // Upload all files in the directory + Files.walk(folderPath).filter(Files::isRegularFile).forEach(filePath -> { + // Calculate relative path from the base folder + String relativePath = folderPath.relativize(filePath).toString().replace('\\', '/'); + // Create blob client for each file + BlobClient blobClient + = new BlobClientBuilder().endpoint(credential.getSasUri()).blobName(relativePath).buildClient(); + // Upload the file + blobClient.upload(BinaryData.fromFile(filePath), true); + }); + // Create a FolderDatasetVersion with the container URL + RequestOptions requestOptions = new RequestOptions(); + FolderDatasetVersion datasetVersion = this + .createOrUpdateDatasetVersionWithResponse(name, version, + BinaryData.fromObject(new FolderDatasetVersion().setDataUri(containerUrl)), requestOptions) + .getValue() + .toObject(FolderDatasetVersion.class); + return datasetVersion; + } + + /** + * List all versions of the given DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listDatasetVersions(String name, RequestOptions requestOptions) { + return this.serviceClient.listDatasetVersions(name, requestOptions); + } + + /** + * List the latest version of each DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listLatestDatasetVersions(RequestOptions requestOptions) { + return this.serviceClient.listLatestDatasetVersions(requestOptions); + } + + /** + * Get the specific version of the DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to retrieve. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the specific version of the DatasetVersion along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getDatasetVersionWithResponse(String name, String version, + RequestOptions requestOptions) { + return this.serviceClient.getDatasetVersionWithResponse(name, version, requestOptions); + } + + /** + * Delete the specific version of the DatasetVersion. + * + * @param name The name of the resource. + * @param version The version of the DatasetVersion to delete. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteDatasetVersionWithResponse(String name, String version, RequestOptions requestOptions) { + return this.serviceClient.deleteDatasetVersionWithResponse(name, version, requestOptions); + } + + /** + * Create a new or update an existing DatasetVersion with the given version id. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to create or replace. + * @param body The definition of the DatasetVersion to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return datasetVersion Definition along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateDatasetVersionWithResponse(String name, String version, BinaryData body, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateDatasetVersionWithResponse(name, version, body, requestOptions); + } + + /** + * List all versions of the given DatasetVersion. + * + * @param name The name of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listDatasetVersions(String name) { + // Generated convenience method for listDatasetVersions + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listDatasetVersions(name, requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(DatasetVersion.class)); + } + + /** + * List the latest version of each DatasetVersion. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listLatestDatasetVersions() { + // Generated convenience method for listLatestDatasetVersions + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listLatestDatasetVersions(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(DatasetVersion.class)); + } + + /** + * Get the specific version of the DatasetVersion. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to retrieve. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specific version of the DatasetVersion. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public DatasetVersion getDatasetVersion(String name, String version) { + // Generated convenience method for getDatasetVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDatasetVersionWithResponse(name, version, requestOptions).getValue().toObject(DatasetVersion.class); + } + + /** + * Delete the specific version of the DatasetVersion. + * + * @param name The name of the resource. + * @param version The version of the DatasetVersion to delete. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void deleteDatasetVersion(String name, String version) { + // Generated convenience method for deleteDatasetVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteDatasetVersionWithResponse(name, version, requestOptions).getValue(); + } + + /** + * Create a new or update an existing DatasetVersion with the given version id. + * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to create or replace. + * @param body The definition of the DatasetVersion to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return datasetVersion Definition. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public DatasetVersion createOrUpdateDatasetVersion(String name, String version, DatasetVersion body) { + // Generated convenience method for createOrUpdateDatasetVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + JsonMergePatchHelper.getDatasetVersionAccessor().prepareModelForJsonMergePatch(body, true); + BinaryData bodyInBinaryData = BinaryData.fromObject(body); + // BinaryData.fromObject() will not fire serialization, use getLength() to fire serialization. + bodyInBinaryData.getLength(); + JsonMergePatchHelper.getDatasetVersionAccessor().prepareModelForJsonMergePatch(body, false); + return createOrUpdateDatasetVersionWithResponse(name, version, bodyInBinaryData, requestOptions).getValue() + .toObject(DatasetVersion.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DeploymentsAsyncClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DeploymentsAsyncClient.java new file mode 100644 index 000000000000..a7033ad284fe --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DeploymentsAsyncClient.java @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.DeploymentsImpl; +import com.azure.ai.projects.models.Deployment; +import com.azure.ai.projects.models.DeploymentType; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import java.util.stream.Collectors; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class, isAsync = true) +public final class DeploymentsAsyncClient { + + @Generated + private final DeploymentsImpl serviceClient; + + /** + * Initializes an instance of DeploymentsAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + DeploymentsAsyncClient(DeploymentsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Get a deployed model. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param name Name of the deployment. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a deployed model along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getDeploymentWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getDeploymentWithResponseAsync(name, requestOptions); + } + + /** + * List all deployed models in the project. + *

Query Parameters

+ * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
modelPublisherStringNoModel publisher to filter models by
modelNameStringNoModel name (the publisher specific name) to filter models + * by
deploymentTypeStringNoType of deployment to filter list by. Allowed values: + * "ModelDeployment".
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Deployment items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listDeployments(RequestOptions requestOptions) { + return this.serviceClient.listDeploymentsAsync(requestOptions); + } + + /** + * Get a deployed model. + * + * @param name Name of the deployment. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a deployed model on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getDeployment(String name) { + // Generated convenience method for getDeploymentWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDeploymentWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(Deployment.class)); + } + + /** + * List all deployed models in the project. + * + * @param modelPublisher Model publisher to filter models by. + * @param modelName Model name (the publisher specific name) to filter models by. + * @param deploymentType Type of deployment to filter list by. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Deployment items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listDeployments(String modelPublisher, String modelName, + DeploymentType deploymentType) { + // Generated convenience method for listDeployments + RequestOptions requestOptions = new RequestOptions(); + if (modelPublisher != null) { + requestOptions.addQueryParam("modelPublisher", modelPublisher, false); + } + if (modelName != null) { + requestOptions.addQueryParam("modelName", modelName, false); + } + if (deploymentType != null) { + requestOptions.addQueryParam("deploymentType", deploymentType.toString(), false); + } + PagedFlux pagedFluxResponse = listDeployments(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(Deployment.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * List all deployed models in the project. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Deployment items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listDeployments() { + // Generated convenience method for listDeployments + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listDeployments(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(Deployment.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DeploymentsClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DeploymentsClient.java new file mode 100644 index 000000000000..7831dd5416b2 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/DeploymentsClient.java @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.DeploymentsImpl; +import com.azure.ai.projects.models.Deployment; +import com.azure.ai.projects.models.DeploymentType; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; + +/** + * Initializes a new instance of the synchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class) +public final class DeploymentsClient { + + @Generated + private final DeploymentsImpl serviceClient; + + /** + * Initializes an instance of DeploymentsClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + DeploymentsClient(DeploymentsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Get a deployed model. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param name Name of the deployment. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a deployed model along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getDeploymentWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getDeploymentWithResponse(name, requestOptions); + } + + /** + * List all deployed models in the project. + *

Query Parameters

+ * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
modelPublisherStringNoModel publisher to filter models by
modelNameStringNoModel name (the publisher specific name) to filter models + * by
deploymentTypeStringNoType of deployment to filter list by. Allowed values: + * "ModelDeployment".
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Deployment items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listDeployments(RequestOptions requestOptions) { + return this.serviceClient.listDeployments(requestOptions); + } + + /** + * Get a deployed model. + * + * @param name Name of the deployment. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a deployed model. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Deployment getDeployment(String name) { + // Generated convenience method for getDeploymentWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDeploymentWithResponse(name, requestOptions).getValue().toObject(Deployment.class); + } + + /** + * List all deployed models in the project. + * + * @param modelPublisher Model publisher to filter models by. + * @param modelName Model name (the publisher specific name) to filter models by. + * @param deploymentType Type of deployment to filter list by. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Deployment items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listDeployments(String modelPublisher, String modelName, + DeploymentType deploymentType) { + // Generated convenience method for listDeployments + RequestOptions requestOptions = new RequestOptions(); + if (modelPublisher != null) { + requestOptions.addQueryParam("modelPublisher", modelPublisher, false); + } + if (modelName != null) { + requestOptions.addQueryParam("modelName", modelName, false); + } + if (deploymentType != null) { + requestOptions.addQueryParam("deploymentType", deploymentType.toString(), false); + } + return serviceClient.listDeployments(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(Deployment.class)); + } + + /** + * List all deployed models in the project. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Deployment items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listDeployments() { + // Generated convenience method for listDeployments + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listDeployments(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(Deployment.class)); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/EvaluationsAsyncClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/EvaluationsAsyncClient.java new file mode 100644 index 000000000000..77bea48dd861 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/EvaluationsAsyncClient.java @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.EvaluationsImpl; +import com.azure.ai.projects.models.AgentEvaluation; +import com.azure.ai.projects.models.AgentEvaluationRequest; +import com.azure.ai.projects.models.Evaluation; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import java.util.stream.Collectors; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class, isAsync = true) +public final class EvaluationsAsyncClient { + + @Generated + private final EvaluationsImpl serviceClient; + + /** + * Initializes an instance of EvaluationsAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + EvaluationsAsyncClient(EvaluationsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates an agent evaluation run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     runId: String (Required)
+     *     threadId: String (Optional)
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     *     samplingConfiguration (Optional): {
+     *         name: String (Required)
+     *         samplingPercent: double (Required)
+     *         maxRequestRate: double (Required)
+     *     }
+     *     redactionConfiguration (Optional): {
+     *         redactScoreProperties: Boolean (Optional)
+     *     }
+     *     appInsightsConnectionString: String (Required)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     status: String (Required)
+     *     error: String (Optional)
+     *     result (Optional): [
+     *          (Optional){
+     *             evaluator: String (Required)
+     *             evaluatorId: String (Required)
+     *             score: double (Required)
+     *             status: String (Required)
+     *             reason: String (Optional)
+     *             version: String (Optional)
+     *             threadId: String (Optional)
+     *             runId: String (Required)
+     *             error: String (Optional)
+     *             additionalDetails (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param evaluation Agent evaluation to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return evaluation response for agent evaluation run along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createAgentEvaluationWithResponse(BinaryData evaluation, + RequestOptions requestOptions) { + return this.serviceClient.createAgentEvaluationWithResponseAsync(evaluation, requestOptions); + } + + /** + * Creates an agent evaluation run. + * + * @param evaluation Agent evaluation to be run. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return evaluation response for agent evaluation run on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createAgentEvaluation(AgentEvaluationRequest evaluation) { + // Generated convenience method for createAgentEvaluationWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createAgentEvaluationWithResponse(BinaryData.fromObject(evaluation), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(AgentEvaluation.class)); + } + + /** + * Get an evaluation run by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name Identifier of the evaluation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return an evaluation run by name along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getEvaluationWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getEvaluationWithResponseAsync(name, requestOptions); + } + + /** + * List evaluation runs. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Evaluation items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listEvaluations(RequestOptions requestOptions) { + return this.serviceClient.listEvaluationsAsync(requestOptions); + } + + /** + * Creates an evaluation run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param evaluation Evaluation to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return evaluation Definition along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createEvaluationWithResponse(BinaryData evaluation, + RequestOptions requestOptions) { + return this.serviceClient.createEvaluationWithResponseAsync(evaluation, requestOptions); + } + + /** + * Get an evaluation run by name. + * + * @param name Identifier of the evaluation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an evaluation run by name on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getEvaluation(String name) { + // Generated convenience method for getEvaluationWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getEvaluationWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(Evaluation.class)); + } + + /** + * List evaluation runs. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Evaluation items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listEvaluations() { + // Generated convenience method for listEvaluations + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listEvaluations(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(Evaluation.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * Creates an evaluation run. + * + * @param evaluation Evaluation to be run. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return evaluation Definition on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createEvaluation(Evaluation evaluation) { + // Generated convenience method for createEvaluationWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createEvaluationWithResponse(BinaryData.fromObject(evaluation), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(Evaluation.class)); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/EvaluationsClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/EvaluationsClient.java new file mode 100644 index 000000000000..cda7767cb291 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/EvaluationsClient.java @@ -0,0 +1,377 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.EvaluationsImpl; +import com.azure.ai.projects.models.AgentEvaluation; +import com.azure.ai.projects.models.AgentEvaluationRequest; +import com.azure.ai.projects.models.Evaluation; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; + +/** + * Initializes a new instance of the synchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class) +public final class EvaluationsClient { + + @Generated + private final EvaluationsImpl serviceClient; + + /** + * Initializes an instance of EvaluationsClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + EvaluationsClient(EvaluationsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Creates an agent evaluation run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     runId: String (Required)
+     *     threadId: String (Optional)
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     *     samplingConfiguration (Optional): {
+     *         name: String (Required)
+     *         samplingPercent: double (Required)
+     *         maxRequestRate: double (Required)
+     *     }
+     *     redactionConfiguration (Optional): {
+     *         redactScoreProperties: Boolean (Optional)
+     *     }
+     *     appInsightsConnectionString: String (Required)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     status: String (Required)
+     *     error: String (Optional)
+     *     result (Optional): [
+     *          (Optional){
+     *             evaluator: String (Required)
+     *             evaluatorId: String (Required)
+     *             score: double (Required)
+     *             status: String (Required)
+     *             reason: String (Optional)
+     *             version: String (Optional)
+     *             threadId: String (Optional)
+     *             runId: String (Required)
+     *             error: String (Optional)
+     *             additionalDetails (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param evaluation Agent evaluation to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return evaluation response for agent evaluation run along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createAgentEvaluationWithResponse(BinaryData evaluation, + RequestOptions requestOptions) { + return this.serviceClient.createAgentEvaluationWithResponse(evaluation, requestOptions); + } + + /** + * Creates an agent evaluation run. + * + * @param evaluation Agent evaluation to be run. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return evaluation response for agent evaluation run. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public AgentEvaluation createAgentEvaluation(AgentEvaluationRequest evaluation) { + // Generated convenience method for createAgentEvaluationWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createAgentEvaluationWithResponse(BinaryData.fromObject(evaluation), requestOptions).getValue() + .toObject(AgentEvaluation.class); + } + + /** + * Get an evaluation run by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name Identifier of the evaluation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return an evaluation run by name along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getEvaluationWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getEvaluationWithResponse(name, requestOptions); + } + + /** + * List evaluation runs. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Evaluation items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listEvaluations(RequestOptions requestOptions) { + return this.serviceClient.listEvaluations(requestOptions); + } + + /** + * Creates an evaluation run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param evaluation Evaluation to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return evaluation Definition along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createEvaluationWithResponse(BinaryData evaluation, RequestOptions requestOptions) { + return this.serviceClient.createEvaluationWithResponse(evaluation, requestOptions); + } + + /** + * Get an evaluation run by name. + * + * @param name Identifier of the evaluation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return an evaluation run by name. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Evaluation getEvaluation(String name) { + // Generated convenience method for getEvaluationWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getEvaluationWithResponse(name, requestOptions).getValue().toObject(Evaluation.class); + } + + /** + * List evaluation runs. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Evaluation items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listEvaluations() { + // Generated convenience method for listEvaluations + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listEvaluations(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(Evaluation.class)); + } + + /** + * Creates an evaluation run. + * + * @param evaluation Evaluation to be run. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return evaluation Definition. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Evaluation createEvaluation(Evaluation evaluation) { + // Generated convenience method for createEvaluationWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createEvaluationWithResponse(BinaryData.fromObject(evaluation), requestOptions).getValue() + .toObject(Evaluation.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/IndexesAsyncClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/IndexesAsyncClient.java new file mode 100644 index 000000000000..b304064028cd --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/IndexesAsyncClient.java @@ -0,0 +1,352 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.IndexesImpl; +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.ai.projects.models.Index; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import java.util.stream.Collectors; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class, isAsync = true) +public final class IndexesAsyncClient { + + @Generated + private final IndexesImpl serviceClient; + + /** + * Initializes an instance of IndexesAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + IndexesAsyncClient(IndexesImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * List all versions of the given Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listIndexVersions(String name, RequestOptions requestOptions) { + return this.serviceClient.listIndexVersionsAsync(name, requestOptions); + } + + /** + * List the latest version of each Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listLatestIndexVersions(RequestOptions requestOptions) { + return this.serviceClient.listLatestIndexVersionsAsync(requestOptions); + } + + /** + * Get the specific version of the Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the Index to retrieve. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the specific version of the Index along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getIndexVersionWithResponse(String name, String version, + RequestOptions requestOptions) { + return this.serviceClient.getIndexVersionWithResponseAsync(name, version, requestOptions); + } + + /** + * Delete the specific version of the Index. + * + * @param name The name of the resource. + * @param version The version of the Index to delete. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteIndexVersionWithResponse(String name, String version, + RequestOptions requestOptions) { + return this.serviceClient.deleteIndexVersionWithResponseAsync(name, version, requestOptions); + } + + /** + * Create a new or update an existing Index with the given version id. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the Index to create or replace. + * @param body The definition of the Index to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return index resource Definition along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateIndexVersionWithResponse(String name, String version, + BinaryData body, RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateIndexVersionWithResponseAsync(name, version, body, requestOptions); + } + + /** + * List all versions of the given Index. + * + * @param name The name of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Index items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listIndexVersions(String name) { + // Generated convenience method for listIndexVersions + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listIndexVersions(name, requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(Index.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * List the latest version of each Index. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Index items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listLatestIndexVersions() { + // Generated convenience method for listLatestIndexVersions + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listLatestIndexVersions(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(Index.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * Get the specific version of the Index. + * + * @param name The name of the resource. + * @param version The specific version id of the Index to retrieve. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specific version of the Index on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getIndexVersion(String name, String version) { + // Generated convenience method for getIndexVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexVersionWithResponse(name, version, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(Index.class)); + } + + /** + * Delete the specific version of the Index. + * + * @param name The name of the resource. + * @param version The version of the Index to delete. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return A {@link Mono} that completes when a successful response is received. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono deleteIndexVersion(String name, String version) { + // Generated convenience method for deleteIndexVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteIndexVersionWithResponse(name, version, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Create a new or update an existing Index with the given version id. + * + * @param name The name of the resource. + * @param version The specific version id of the Index to create or replace. + * @param body The definition of the Index to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return index resource Definition on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdateIndexVersion(String name, String version, Index body) { + // Generated convenience method for createOrUpdateIndexVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + JsonMergePatchHelper.getIndexAccessor().prepareModelForJsonMergePatch(body, true); + BinaryData bodyInBinaryData = BinaryData.fromObject(body); + // BinaryData.fromObject() will not fire serialization, use getLength() to fire serialization. + bodyInBinaryData.getLength(); + JsonMergePatchHelper.getIndexAccessor().prepareModelForJsonMergePatch(body, false); + return createOrUpdateIndexVersionWithResponse(name, version, bodyInBinaryData, requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(Index.class)); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/IndexesClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/IndexesClient.java new file mode 100644 index 000000000000..f37b7d1982f8 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/IndexesClient.java @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.IndexesImpl; +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.ai.projects.models.Index; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; + +/** + * Initializes a new instance of the synchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class) +public final class IndexesClient { + + @Generated + private final IndexesImpl serviceClient; + + /** + * Initializes an instance of IndexesClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + IndexesClient(IndexesImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * List all versions of the given Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listIndexVersions(String name, RequestOptions requestOptions) { + return this.serviceClient.listIndexVersions(name, requestOptions); + } + + /** + * List the latest version of each Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listLatestIndexVersions(RequestOptions requestOptions) { + return this.serviceClient.listLatestIndexVersions(requestOptions); + } + + /** + * Get the specific version of the Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the Index to retrieve. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the specific version of the Index along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getIndexVersionWithResponse(String name, String version, + RequestOptions requestOptions) { + return this.serviceClient.getIndexVersionWithResponse(name, version, requestOptions); + } + + /** + * Delete the specific version of the Index. + * + * @param name The name of the resource. + * @param version The version of the Index to delete. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteIndexVersionWithResponse(String name, String version, RequestOptions requestOptions) { + return this.serviceClient.deleteIndexVersionWithResponse(name, version, requestOptions); + } + + /** + * Create a new or update an existing Index with the given version id. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the Index to create or replace. + * @param body The definition of the Index to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return index resource Definition along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateIndexVersionWithResponse(String name, String version, BinaryData body, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateIndexVersionWithResponse(name, version, body, requestOptions); + } + + /** + * List all versions of the given Index. + * + * @param name The name of the resource. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Index items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listIndexVersions(String name) { + // Generated convenience method for listIndexVersions + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listIndexVersions(name, requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(Index.class)); + } + + /** + * List the latest version of each Index. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of Index items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listLatestIndexVersions() { + // Generated convenience method for listLatestIndexVersions + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listLatestIndexVersions(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(Index.class)); + } + + /** + * Get the specific version of the Index. + * + * @param name The name of the resource. + * @param version The specific version id of the Index to retrieve. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the specific version of the Index. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Index getIndexVersion(String name, String version) { + // Generated convenience method for getIndexVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexVersionWithResponse(name, version, requestOptions).getValue().toObject(Index.class); + } + + /** + * Delete the specific version of the Index. + * + * @param name The name of the resource. + * @param version The version of the Index to delete. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void deleteIndexVersion(String name, String version) { + // Generated convenience method for deleteIndexVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteIndexVersionWithResponse(name, version, requestOptions).getValue(); + } + + /** + * Create a new or update an existing Index with the given version id. + * + * @param name The name of the resource. + * @param version The specific version id of the Index to create or replace. + * @param body The definition of the Index to create or update. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return index resource Definition. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Index createOrUpdateIndexVersion(String name, String version, Index body) { + // Generated convenience method for createOrUpdateIndexVersionWithResponse + RequestOptions requestOptions = new RequestOptions(); + JsonMergePatchHelper.getIndexAccessor().prepareModelForJsonMergePatch(body, true); + BinaryData bodyInBinaryData = BinaryData.fromObject(body); + // BinaryData.fromObject() will not fire serialization, use getLength() to fire serialization. + bodyInBinaryData.getLength(); + JsonMergePatchHelper.getIndexAccessor().prepareModelForJsonMergePatch(body, false); + return createOrUpdateIndexVersionWithResponse(name, version, bodyInBinaryData, requestOptions).getValue() + .toObject(Index.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/ProjectsServiceVersion.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/ProjectsServiceVersion.java new file mode 100644 index 000000000000..2e2c7719dfec --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/ProjectsServiceVersion.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.projects; + +import com.azure.core.util.ServiceVersion; + +/** + * Service version of ProjectsClient. + */ +public enum ProjectsServiceVersion implements ServiceVersion { + /** + * Enum value 2025-05-01. + */ + V2025_05_01("2025-05-01"), + + /** + * Enum value 2025-05-15-preview. + */ + V2025_05_15_PREVIEW("2025-05-15-preview"); + + private final String version; + + ProjectsServiceVersion(String version) { + this.version = version; + } + + /** + * {@inheritDoc} + */ + @Override + public String getVersion() { + return this.version; + } + + /** + * Gets the latest service version supported by this client library. + * + * @return The latest {@link ProjectsServiceVersion}. + */ + public static ProjectsServiceVersion getLatest() { + return V2025_05_15_PREVIEW; + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/RedTeamsAsyncClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/RedTeamsAsyncClient.java new file mode 100644 index 000000000000..fee0a5f7ac2d --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/RedTeamsAsyncClient.java @@ -0,0 +1,284 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.RedTeamsImpl; +import com.azure.ai.projects.models.RedTeam; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.FluxUtil; +import java.util.stream.Collectors; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class, isAsync = true) +public final class RedTeamsAsyncClient { + + @Generated + private final RedTeamsImpl serviceClient; + + /** + * Initializes an instance of RedTeamsAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + RedTeamsAsyncClient(RedTeamsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Get a redteam by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name Identifier of the red team run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a redteam by name along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getRedTeamWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getRedTeamWithResponseAsync(name, requestOptions); + } + + /** + * List a redteam by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of RedTeam items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listRedTeams(RequestOptions requestOptions) { + return this.serviceClient.listRedTeamsAsync(requestOptions); + } + + /** + * Creates a redteam run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param redTeam Redteam to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return red team details along with {@link Response} on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createRedTeamWithResponse(BinaryData redTeam, RequestOptions requestOptions) { + return this.serviceClient.createRedTeamWithResponseAsync(redTeam, requestOptions); + } + + /** + * Get a redteam by name. + * + * @param name Identifier of the red team run. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a redteam by name on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getRedTeam(String name) { + // Generated convenience method for getRedTeamWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getRedTeamWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(RedTeam.class)); + } + + /** + * List a redteam by name. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of RedTeam items as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listRedTeams() { + // Generated convenience method for listRedTeams + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listRedTeams(requestOptions); + return PagedFlux.create(() -> (continuationTokenParam, pageSizeParam) -> { + Flux> flux = (continuationTokenParam == null) + ? pagedFluxResponse.byPage().take(1) + : pagedFluxResponse.byPage(continuationTokenParam).take(1); + return flux.map(pagedResponse -> new PagedResponseBase(pagedResponse.getRequest(), + pagedResponse.getStatusCode(), pagedResponse.getHeaders(), + pagedResponse.getValue() + .stream() + .map(protocolMethodData -> protocolMethodData.toObject(RedTeam.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * Creates a redteam run. + * + * @param redTeam Redteam to be run. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return red team details on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createRedTeam(RedTeam redTeam) { + // Generated convenience method for createRedTeamWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createRedTeamWithResponse(BinaryData.fromObject(redTeam), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(RedTeam.class)); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/RedTeamsClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/RedTeamsClient.java new file mode 100644 index 000000000000..e82e814a873a --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/RedTeamsClient.java @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.implementation.RedTeamsImpl; +import com.azure.ai.projects.models.RedTeam; +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; + +/** + * Initializes a new instance of the synchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class) +public final class RedTeamsClient { + + @Generated + private final RedTeamsImpl serviceClient; + + /** + * Initializes an instance of RedTeamsClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + RedTeamsClient(RedTeamsImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Get a redteam by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name Identifier of the red team run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a redteam by name along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getRedTeamWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getRedTeamWithResponse(name, requestOptions); + } + + /** + * List a redteam by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of RedTeam items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listRedTeams(RequestOptions requestOptions) { + return this.serviceClient.listRedTeams(requestOptions); + } + + /** + * Creates a redteam run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param redTeam Redteam to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return red team details along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createRedTeamWithResponse(BinaryData redTeam, RequestOptions requestOptions) { + return this.serviceClient.createRedTeamWithResponse(redTeam, requestOptions); + } + + /** + * Get a redteam by name. + * + * @param name Identifier of the red team run. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a redteam by name. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public RedTeam getRedTeam(String name) { + // Generated convenience method for getRedTeamWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getRedTeamWithResponse(name, requestOptions).getValue().toObject(RedTeam.class); + } + + /** + * List a redteam by name. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return paged collection of RedTeam items as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listRedTeams() { + // Generated convenience method for listRedTeams + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listRedTeams(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(RedTeam.class)); + } + + /** + * Creates a redteam run. + * + * @param redTeam Redteam to be run. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return red team details. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public RedTeam createRedTeam(RedTeam redTeam) { + // Generated convenience method for createRedTeamWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createRedTeamWithResponse(BinaryData.fromObject(redTeam), requestOptions).getValue() + .toObject(RedTeam.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/TelemetryAsyncClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/TelemetryAsyncClient.java new file mode 100644 index 000000000000..35a68a9265b5 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/TelemetryAsyncClient.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.ConnectionType; +import com.azure.ai.projects.models.CredentialType; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.AzureException; +import com.azure.core.util.logging.ClientLogger; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class, isAsync = true) +public final class TelemetryAsyncClient { + + private final ConnectionsAsyncClient connectionsAsyncClient; + private final ClientLogger logger = new ClientLogger(TelemetryAsyncClient.class); + + /** + * Initializes an instance of TelemetryAsyncClient class. + * + * @param connectionsAsyncClient the connections async client implementation. + */ + TelemetryAsyncClient(ConnectionsAsyncClient connectionsAsyncClient) { + this.connectionsAsyncClient = connectionsAsyncClient; + } + + /** + * Get the Application Insights connection string associated with the Project's Application Insights resource. + * + * @return The Application Insights connection string if a the resource was enabled for the Project. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getConnectionString() { + return connectionsAsyncClient.listConnections(ConnectionType.APPLICATION_INSIGHTS, true) + .collectList() + .flatMap(connections -> { + if (connections.isEmpty()) { + return Mono.error( + logger.logExceptionAsError(new AzureException("No Application Insights connection found."))); + } + + String connectionName = connections.get(0).getName(); + return connectionsAsyncClient.getConnectionWithCredentials(connectionName).flatMap(connection -> { + if (connection.getCredentials().getType() != CredentialType.API_KEY) { + return Mono.error(logger.logExceptionAsError( + new AzureException("Application Insights connection does not use API Key credentials."))); + } + + if (connection.getId() == null || connection.getId().isEmpty()) { + return Mono.error(logger.logExceptionAsError( + new AzureException("Application Insights connection does not have a connection string."))); + } + + return Mono.just(connection.getId()); + }); + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/TelemetryClient.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/TelemetryClient.java new file mode 100644 index 000000000000..f0133c77b362 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/TelemetryClient.java @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.Connection; +import com.azure.ai.projects.models.ConnectionType; +import com.azure.ai.projects.models.CredentialType; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.exception.AzureException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.logging.ClientLogger; +import java.util.Iterator; + +/** + * Initializes a new instance of the synchronous AIProjectClient type. + */ +@ServiceClient(builder = AIProjectClientBuilder.class) +public final class TelemetryClient { + + private final ConnectionsClient connectionsClient; + private final ClientLogger logger = new ClientLogger(TelemetryClient.class); + private static final String ENV_CONTENT_RECORDING_ENABLED = "AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED"; + + /** + * Initializes an instance of TelemetryClient class. + * + * @param connectionsClient the connections client implementation. + */ + TelemetryClient(ConnectionsClient connectionsClient) { + this.connectionsClient = connectionsClient; + } + + /** + * Get the Application Insights connection string associated with the Project's Application Insights resource. + * + * @return The Application Insights connection string if the resource was enabled for the Project. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public String getConnectionString() { + PagedIterable connections + = connectionsClient.listConnections(ConnectionType.APPLICATION_INSIGHTS, true); + Iterator iterator = connections.iterator(); + + if (iterator.hasNext()) { + Connection connection = connectionsClient.getConnection(iterator.next().getName(), true); + if (connection.getCredentials().getType() == CredentialType.API_KEY) { + if (connection.getId() != null) { + return connection.getId(); + } else { + throw logger.logExceptionAsError( + new AzureException("Application Insights connection does not have a connection string.")); + } + } else { + throw logger.logExceptionAsError( + new AzureException("Application Insights connection does not use API Key credentials.")); + } + } else { + throw logger.logExceptionAsError(new AzureException("No Application Insights connection found.")); + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/AIProjectClientImpl.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/AIProjectClientImpl.java new file mode 100644 index 000000000000..4628d2214cb6 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/AIProjectClientImpl.java @@ -0,0 +1,227 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.projects.implementation; + +import com.azure.ai.projects.ProjectsServiceVersion; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.core.util.serializer.SerializerAdapter; + +/** + * Initializes a new instance of the AIProjectClient type. + */ +public final class AIProjectClientImpl { + /** + * 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. + */ + private final String endpoint; + + /** + * Gets 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. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Service version. + */ + private final ProjectsServiceVersion serviceVersion; + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public ProjectsServiceVersion getServiceVersion() { + return this.serviceVersion; + } + + /** + * The HTTP pipeline to send requests through. + */ + private final HttpPipeline httpPipeline; + + /** + * Gets The HTTP pipeline to send requests through. + * + * @return the httpPipeline value. + */ + public HttpPipeline getHttpPipeline() { + return this.httpPipeline; + } + + /** + * The serializer to serialize an object into a string. + */ + private final SerializerAdapter serializerAdapter; + + /** + * Gets The serializer to serialize an object into a string. + * + * @return the serializerAdapter value. + */ + public SerializerAdapter getSerializerAdapter() { + return this.serializerAdapter; + } + + /** + * The ConnectionsImpl object to access its operations. + */ + private final ConnectionsImpl connections; + + /** + * Gets the ConnectionsImpl object to access its operations. + * + * @return the ConnectionsImpl object. + */ + public ConnectionsImpl getConnections() { + return this.connections; + } + + /** + * The EvaluationsImpl object to access its operations. + */ + private final EvaluationsImpl evaluations; + + /** + * Gets the EvaluationsImpl object to access its operations. + * + * @return the EvaluationsImpl object. + */ + public EvaluationsImpl getEvaluations() { + return this.evaluations; + } + + /** + * The DatasetsImpl object to access its operations. + */ + private final DatasetsImpl datasets; + + /** + * Gets the DatasetsImpl object to access its operations. + * + * @return the DatasetsImpl object. + */ + public DatasetsImpl getDatasets() { + return this.datasets; + } + + /** + * The IndexesImpl object to access its operations. + */ + private final IndexesImpl indexes; + + /** + * Gets the IndexesImpl object to access its operations. + * + * @return the IndexesImpl object. + */ + public IndexesImpl getIndexes() { + return this.indexes; + } + + /** + * The DeploymentsImpl object to access its operations. + */ + private final DeploymentsImpl deployments; + + /** + * Gets the DeploymentsImpl object to access its operations. + * + * @return the DeploymentsImpl object. + */ + public DeploymentsImpl getDeployments() { + return this.deployments; + } + + /** + * The RedTeamsImpl object to access its operations. + */ + private final RedTeamsImpl redTeams; + + /** + * Gets the RedTeamsImpl object to access its operations. + * + * @return the RedTeamsImpl object. + */ + public RedTeamsImpl getRedTeams() { + return this.redTeams; + } + + /** + * Initializes an instance of AIProjectClient client. + * + * @param endpoint 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. + * @param serviceVersion Service version. + */ + public AIProjectClientImpl(String endpoint, ProjectsServiceVersion serviceVersion) { + this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), + JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion); + } + + /** + * Initializes an instance of AIProjectClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param endpoint 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. + * @param serviceVersion Service version. + */ + public AIProjectClientImpl(HttpPipeline httpPipeline, String endpoint, ProjectsServiceVersion serviceVersion) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion); + } + + /** + * Initializes an instance of AIProjectClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param serializerAdapter The serializer to serialize an object into a string. + * @param endpoint 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. + * @param serviceVersion Service version. + */ + public AIProjectClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, + ProjectsServiceVersion serviceVersion) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.endpoint = endpoint; + this.serviceVersion = serviceVersion; + this.connections = new ConnectionsImpl(this); + this.evaluations = new EvaluationsImpl(this); + this.datasets = new DatasetsImpl(this); + this.indexes = new IndexesImpl(this); + this.deployments = new DeploymentsImpl(this); + this.redTeams = new RedTeamsImpl(this); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/ConnectionsImpl.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/ConnectionsImpl.java new file mode 100644 index 000000000000..6be56cfbbd77 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/ConnectionsImpl.java @@ -0,0 +1,609 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.projects.implementation; + +import com.azure.ai.projects.ProjectsServiceVersion; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in Connections. + */ +public final class ConnectionsImpl { + /** + * The proxy service used to perform REST calls. + */ + private final ConnectionsService service; + + /** + * The service client containing this operation class. + */ + private final AIProjectClientImpl client; + + /** + * Initializes an instance of ConnectionsImpl. + * + * @param client the instance of the service client containing this operation class. + */ + ConnectionsImpl(AIProjectClientImpl client) { + this.service + = RestProxy.create(ConnectionsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public ProjectsServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for AIProjectClientConnections to be used by the proxy service to perform + * REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "AIProjectClientConne") + public interface ConnectionsService { + @Get("/connections/{name}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getConnection(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/connections/{name}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getConnectionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Post("/connections/{name}/getConnectionWithCredentials") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getConnectionWithCredentials(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Post("/connections/{name}/getConnectionWithCredentials") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getConnectionWithCredentialsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/connections") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listConnections(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/connections") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listConnectionsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listConnectionsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listConnectionsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + } + + /** + * Get a connection by name, without populating connection credentials. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The friendly name of the connection, provided by the user. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a connection by name, without populating connection credentials along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getConnectionWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getConnection(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, accept, requestOptions, context)); + } + + /** + * Get a connection by name, without populating connection credentials. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The friendly name of the connection, provided by the user. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a connection by name, without populating connection credentials along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getConnectionWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getConnectionSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), name, + accept, requestOptions, Context.NONE); + } + + /** + * Get a connection by name, with its connection credentials. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The friendly name of the connection, provided by the user. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a connection by name, with its connection credentials along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getConnectionWithCredentialsWithResponseAsync(String name, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getConnectionWithCredentials(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, accept, requestOptions, context)); + } + + /** + * Get a connection by name, with its connection credentials. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The friendly name of the connection, provided by the user. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a connection by name, with its connection credentials along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getConnectionWithCredentialsWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getConnectionWithCredentialsSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, accept, requestOptions, Context.NONE); + } + + /** + * List all connections in the project, without populating connection credentials. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
connectionTypeStringNoList connections of this specific type. Allowed values: + * "AzureOpenAI", "AzureBlob", "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", "AppConfig", + * "AppInsights", "CustomKeys".
defaultConnectionBooleanNoList connections that are default + * connections
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Connection items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listConnectionsSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listConnections(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * List all connections in the project, without populating connection credentials. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
connectionTypeStringNoList connections of this specific type. Allowed values: + * "AzureOpenAI", "AzureBlob", "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", "AppConfig", + * "AppInsights", "CustomKeys".
defaultConnectionBooleanNoList connections that are default + * connections
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Connection items as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listConnectionsAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> listConnectionsSinglePageAsync(requestOptions), + nextLink -> listConnectionsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); + } + + /** + * List all connections in the project, without populating connection credentials. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
connectionTypeStringNoList connections of this specific type. Allowed values: + * "AzureOpenAI", "AzureBlob", "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", "AppConfig", + * "AppInsights", "CustomKeys".
defaultConnectionBooleanNoList connections that are default + * connections
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Connection items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listConnectionsSinglePage(RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listConnectionsSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + /** + * List all connections in the project, without populating connection credentials. + *

Query Parameters

+ * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
connectionTypeStringNoList connections of this specific type. Allowed values: + * "AzureOpenAI", "AzureBlob", "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", "AppConfig", + * "AppInsights", "CustomKeys".
defaultConnectionBooleanNoList connections that are default + * connections
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Connection items as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listConnections(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> listConnectionsSinglePage(requestOptions), + nextLink -> listConnectionsNextSinglePage(nextLink, requestOptionsForNextPage)); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Connection items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listConnectionsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listConnectionsNext(nextLink, this.client.getEndpoint(), accept, + requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     id: String (Required)
+     *     type: String(AzureOpenAI/AzureBlob/AzureStorageAccount/CognitiveSearch/CosmosDB/ApiKey/AppConfig/AppInsights/CustomKeys) (Required)
+     *     target: String (Required)
+     *     isDefault: boolean (Required)
+     *     credentials (Required): {
+     *         type: String(ApiKey/AAD/SAS/CustomKeys/None) (Required)
+     *     }
+     *     metadata (Required): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Connection items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listConnectionsNextSinglePage(String nextLink, RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listConnectionsNextSync(nextLink, this.client.getEndpoint(), accept, + requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/DatasetsImpl.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/DatasetsImpl.java new file mode 100644 index 000000000000..56407b109c14 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/DatasetsImpl.java @@ -0,0 +1,1195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.projects.implementation; + +import com.azure.ai.projects.ProjectsServiceVersion; +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.Patch; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in Datasets. + */ +public final class DatasetsImpl { + /** + * The proxy service used to perform REST calls. + */ + private final DatasetsService service; + + /** + * The service client containing this operation class. + */ + private final AIProjectClientImpl client; + + /** + * Initializes an instance of DatasetsImpl. + * + * @param client the instance of the service client containing this operation class. + */ + DatasetsImpl(AIProjectClientImpl client) { + this.service = RestProxy.create(DatasetsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public ProjectsServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for AIProjectClientDatasets to be used by the proxy service to perform + * REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "AIProjectClientDatas") + public interface DatasetsService { + @Get("/datasets/{name}/versions") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listDatasetVersions(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/datasets/{name}/versions") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listDatasetVersionsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/datasets") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listLatestDatasetVersions(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/datasets") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listLatestDatasetVersionsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/datasets/{name}/versions/{version}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDatasetVersion(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Get("/datasets/{name}/versions/{version}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDatasetVersionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Delete("/datasets/{name}/versions/{version}") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> deleteDatasetVersion(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Delete("/datasets/{name}/versions/{version}") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteDatasetVersionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Patch("/datasets/{name}/versions/{version}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createOrUpdateDatasetVersion(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Content-Type") String contentType, @PathParam("version") String version, + @HeaderParam("Accept") String accept, @BodyParam("application/merge-patch+json") BinaryData body, + RequestOptions requestOptions, Context context); + + @Patch("/datasets/{name}/versions/{version}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createOrUpdateDatasetVersionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Content-Type") String contentType, @PathParam("version") String version, + @HeaderParam("Accept") String accept, @BodyParam("application/merge-patch+json") BinaryData body, + RequestOptions requestOptions, Context context); + + @Post("/datasets/{name}/versions/{version}/startPendingUpload") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> pendingUpload(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData body, + RequestOptions requestOptions, Context context); + + @Post("/datasets/{name}/versions/{version}/startPendingUpload") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response pendingUploadSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData body, + RequestOptions requestOptions, Context context); + + @Post("/datasets/{name}/versions/{version}/credentials") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getCredentials(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Post("/datasets/{name}/versions/{version}/credentials") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getCredentialsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listDatasetVersionsNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listDatasetVersionsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listLatestDatasetVersionsNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listLatestDatasetVersionsNextSync( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + } + + /** + * List all versions of the given DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listDatasetVersionsSinglePageAsync(String name, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listDatasetVersions(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * List all versions of the given DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listDatasetVersionsAsync(String name, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> listDatasetVersionsSinglePageAsync(name, requestOptions), + nextLink -> listDatasetVersionsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); + } + + /** + * List all versions of the given DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listDatasetVersionsSinglePage(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listDatasetVersionsSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + /** + * List all versions of the given DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listDatasetVersions(String name, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> listDatasetVersionsSinglePage(name, requestOptions), + nextLink -> listDatasetVersionsNextSinglePage(nextLink, requestOptionsForNextPage)); + } + + /** + * List the latest version of each DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listLatestDatasetVersionsSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listLatestDatasetVersions(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * List the latest version of each DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listLatestDatasetVersionsAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> listLatestDatasetVersionsSinglePageAsync(requestOptions), + nextLink -> listLatestDatasetVersionsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); + } + + /** + * List the latest version of each DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listLatestDatasetVersionsSinglePage(RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listLatestDatasetVersionsSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + /** + * List the latest version of each DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listLatestDatasetVersions(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> listLatestDatasetVersionsSinglePage(requestOptions), + nextLink -> listLatestDatasetVersionsNextSinglePage(nextLink, requestOptionsForNextPage)); + } + + /** + * Get the specific version of the DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to retrieve. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the specific version of the DatasetVersion along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getDatasetVersionWithResponseAsync(String name, String version, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getDatasetVersion(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, version, accept, requestOptions, context)); + } + + /** + * Get the specific version of the DatasetVersion. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to retrieve. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the specific version of the DatasetVersion along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getDatasetVersionWithResponse(String name, String version, + RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getDatasetVersionSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + name, version, accept, requestOptions, Context.NONE); + } + + /** + * Delete the specific version of the DatasetVersion. + * + * @param name The name of the resource. + * @param version The version of the DatasetVersion to delete. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteDatasetVersionWithResponseAsync(String name, String version, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.deleteDatasetVersion(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, version, accept, requestOptions, context)); + } + + /** + * Delete the specific version of the DatasetVersion. + * + * @param name The name of the resource. + * @param version The version of the DatasetVersion to delete. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteDatasetVersionWithResponse(String name, String version, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.deleteDatasetVersionSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + name, version, accept, requestOptions, Context.NONE); + } + + /** + * Create a new or update an existing DatasetVersion with the given version id. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to create or replace. + * @param body The definition of the DatasetVersion to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return datasetVersion Definition along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateDatasetVersionWithResponseAsync(String name, String version, + BinaryData body, RequestOptions requestOptions) { + final String contentType = "application/merge-patch+json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.createOrUpdateDatasetVersion(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, contentType, version, accept, body, requestOptions, + context)); + } + + /** + * Create a new or update an existing DatasetVersion with the given version id. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to create or replace. + * @param body The definition of the DatasetVersion to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return datasetVersion Definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateDatasetVersionWithResponse(String name, String version, BinaryData body, + RequestOptions requestOptions) { + final String contentType = "application/merge-patch+json"; + final String accept = "application/json"; + return service.createOrUpdateDatasetVersionSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, contentType, version, accept, body, requestOptions, + Context.NONE); + } + + /** + * Start a new or get an existing pending upload of a dataset for a specific version. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     pendingUploadId: String (Optional)
+     *     connectionName: String (Optional)
+     *     pendingUploadType: String(None/BlobReference) (Required)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     blobReference (Required): {
+     *         blobUri: String (Required)
+     *         storageAccountArmId: String (Required)
+     *         credential (Required): {
+     *             sasUri: String (Required)
+     *             type: String (Required)
+     *         }
+     *     }
+     *     pendingUploadId: String (Required)
+     *     version: String (Optional)
+     *     pendingUploadType: String(None/BlobReference) (Required)
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @param body Parameters for the action. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents the response for a pending upload request along with {@link Response} on successful completion + * of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> pendingUploadWithResponseAsync(String name, String version, BinaryData body, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.pendingUpload(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + name, version, contentType, accept, body, requestOptions, context)); + } + + /** + * Start a new or get an existing pending upload of a dataset for a specific version. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     pendingUploadId: String (Optional)
+     *     connectionName: String (Optional)
+     *     pendingUploadType: String(None/BlobReference) (Required)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     blobReference (Required): {
+     *         blobUri: String (Required)
+     *         storageAccountArmId: String (Required)
+     *         credential (Required): {
+     *             sasUri: String (Required)
+     *             type: String (Required)
+     *         }
+     *     }
+     *     pendingUploadId: String (Required)
+     *     version: String (Optional)
+     *     pendingUploadType: String(None/BlobReference) (Required)
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @param body Parameters for the action. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return represents the response for a pending upload request along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response pendingUploadWithResponse(String name, String version, BinaryData body, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.pendingUploadSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), name, + version, contentType, accept, body, requestOptions, Context.NONE); + } + + /** + * Get the SAS credential to access the storage account associated with a Dataset version. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     blobReference (Required): {
+     *         blobUri: String (Required)
+     *         storageAccountArmId: String (Required)
+     *         credential (Required): {
+     *             sasUri: String (Required)
+     *             type: String (Required)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the SAS credential to access the storage account associated with a Dataset version along with + * {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getCredentialsWithResponseAsync(String name, String version, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getCredentials(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, version, accept, requestOptions, context)); + } + + /** + * Get the SAS credential to access the storage account associated with a Dataset version. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     blobReference (Required): {
+     *         blobUri: String (Required)
+     *         storageAccountArmId: String (Required)
+     *         credential (Required): {
+     *             sasUri: String (Required)
+     *             type: String (Required)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the DatasetVersion to operate on. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the SAS credential to access the storage account associated with a Dataset version along with + * {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getCredentialsWithResponse(String name, String version, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getCredentialsSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), name, + version, accept, requestOptions, Context.NONE); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listDatasetVersionsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listDatasetVersionsNext(nextLink, this.client.getEndpoint(), accept, + requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listDatasetVersionsNextSinglePage(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listDatasetVersionsNextSync(nextLink, this.client.getEndpoint(), accept, + requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listLatestDatasetVersionsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listLatestDatasetVersionsNext(nextLink, this.client.getEndpoint(), accept, + requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(uri_file/uri_folder) (Required)
+     *     dataUri: String (Optional, Required on create)
+     *     isReference: Boolean (Optional)
+     *     connectionName: String (Optional)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of DatasetVersion items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listLatestDatasetVersionsNextSinglePage(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listLatestDatasetVersionsNextSync(nextLink, this.client.getEndpoint(), + accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/DeploymentsImpl.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/DeploymentsImpl.java new file mode 100644 index 000000000000..1853974163d7 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/DeploymentsImpl.java @@ -0,0 +1,439 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.projects.implementation; + +import com.azure.ai.projects.ProjectsServiceVersion; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in Deployments. + */ +public final class DeploymentsImpl { + /** + * The proxy service used to perform REST calls. + */ + private final DeploymentsService service; + + /** + * The service client containing this operation class. + */ + private final AIProjectClientImpl client; + + /** + * Initializes an instance of DeploymentsImpl. + * + * @param client the instance of the service client containing this operation class. + */ + DeploymentsImpl(AIProjectClientImpl client) { + this.service + = RestProxy.create(DeploymentsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public ProjectsServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for AIProjectClientDeployments to be used by the proxy service to perform + * REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "AIProjectClientDeplo") + public interface DeploymentsService { + @Get("/deployments/{name}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getDeployment(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/deployments/{name}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getDeploymentSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/deployments") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listDeployments(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/deployments") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listDeploymentsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listDeploymentsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listDeploymentsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + } + + /** + * Get a deployed model. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param name Name of the deployment. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a deployed model along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getDeploymentWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getDeployment(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, accept, requestOptions, context)); + } + + /** + * Get a deployed model. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param name Name of the deployment. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a deployed model along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getDeploymentWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getDeploymentSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), name, + accept, requestOptions, Context.NONE); + } + + /** + * List all deployed models in the project. + *

Query Parameters

+ * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
modelPublisherStringNoModel publisher to filter models by
modelNameStringNoModel name (the publisher specific name) to filter models + * by
deploymentTypeStringNoType of deployment to filter list by. Allowed values: + * "ModelDeployment".
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Deployment items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listDeploymentsSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listDeployments(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * List all deployed models in the project. + *

Query Parameters

+ * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
modelPublisherStringNoModel publisher to filter models by
modelNameStringNoModel name (the publisher specific name) to filter models + * by
deploymentTypeStringNoType of deployment to filter list by. Allowed values: + * "ModelDeployment".
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Deployment items as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listDeploymentsAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> listDeploymentsSinglePageAsync(requestOptions), + nextLink -> listDeploymentsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); + } + + /** + * List all deployed models in the project. + *

Query Parameters

+ * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
modelPublisherStringNoModel publisher to filter models by
modelNameStringNoModel name (the publisher specific name) to filter models + * by
deploymentTypeStringNoType of deployment to filter list by. Allowed values: + * "ModelDeployment".
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Deployment items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listDeploymentsSinglePage(RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listDeploymentsSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + /** + * List all deployed models in the project. + *

Query Parameters

+ * + * + * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
modelPublisherStringNoModel publisher to filter models by
modelNameStringNoModel name (the publisher specific name) to filter models + * by
deploymentTypeStringNoType of deployment to filter list by. Allowed values: + * "ModelDeployment".
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Deployment items as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listDeployments(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> listDeploymentsSinglePage(requestOptions), + nextLink -> listDeploymentsNextSinglePage(nextLink, requestOptionsForNextPage)); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Deployment items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listDeploymentsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listDeploymentsNext(nextLink, this.client.getEndpoint(), accept, + requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(ModelDeployment) (Required)
+     *     name: String (Required)
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Deployment items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listDeploymentsNextSinglePage(String nextLink, RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listDeploymentsNextSync(nextLink, this.client.getEndpoint(), accept, + requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/EvaluationsImpl.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/EvaluationsImpl.java new file mode 100644 index 000000000000..e6bae8e3f531 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/EvaluationsImpl.java @@ -0,0 +1,944 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.projects.implementation; + +import com.azure.ai.projects.ProjectsServiceVersion; +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in Evaluations. + */ +public final class EvaluationsImpl { + /** + * The proxy service used to perform REST calls. + */ + private final EvaluationsService service; + + /** + * The service client containing this operation class. + */ + private final AIProjectClientImpl client; + + /** + * Initializes an instance of EvaluationsImpl. + * + * @param client the instance of the service client containing this operation class. + */ + EvaluationsImpl(AIProjectClientImpl client) { + this.service + = RestProxy.create(EvaluationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public ProjectsServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for AIProjectClientEvaluations to be used by the proxy service to perform + * REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "AIProjectClientEvalu") + public interface EvaluationsService { + @Get("/evaluations/runs/{name}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getEvaluation(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/evaluations/runs/{name}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getEvaluationSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/evaluations/runs") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listEvaluations(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/evaluations/runs") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listEvaluationsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/evaluations/runs:run") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createEvaluation(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData evaluation, + RequestOptions requestOptions, Context context); + + @Post("/evaluations/runs:run") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createEvaluationSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData evaluation, + RequestOptions requestOptions, Context context); + + @Post("/evaluations/runs:runAgent") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createAgentEvaluation(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData evaluation, + RequestOptions requestOptions, Context context); + + @Post("/evaluations/runs:runAgent") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createAgentEvaluationSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData evaluation, + RequestOptions requestOptions, Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listEvaluationsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listEvaluationsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + } + + /** + * Get an evaluation run by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name Identifier of the evaluation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return an evaluation run by name along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getEvaluationWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getEvaluation(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, accept, requestOptions, context)); + } + + /** + * Get an evaluation run by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name Identifier of the evaluation. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return an evaluation run by name along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getEvaluationWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getEvaluationSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), name, + accept, requestOptions, Context.NONE); + } + + /** + * List evaluation runs. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Evaluation items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listEvaluationsSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listEvaluations(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * List evaluation runs. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Evaluation items as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listEvaluationsAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> listEvaluationsSinglePageAsync(requestOptions), + nextLink -> listEvaluationsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); + } + + /** + * List evaluation runs. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Evaluation items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listEvaluationsSinglePage(RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listEvaluationsSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + /** + * List evaluation runs. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Evaluation items as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listEvaluations(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> listEvaluationsSinglePage(requestOptions), + nextLink -> listEvaluationsNextSinglePage(nextLink, requestOptionsForNextPage)); + } + + /** + * Creates an evaluation run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param evaluation Evaluation to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return evaluation Definition along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createEvaluationWithResponseAsync(BinaryData evaluation, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.createEvaluation(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), contentType, accept, evaluation, requestOptions, context)); + } + + /** + * Creates an evaluation run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param evaluation Evaluation to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return evaluation Definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createEvaluationWithResponse(BinaryData evaluation, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createEvaluationSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + contentType, accept, evaluation, requestOptions, Context.NONE); + } + + /** + * Creates an agent evaluation run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     runId: String (Required)
+     *     threadId: String (Optional)
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     *     samplingConfiguration (Optional): {
+     *         name: String (Required)
+     *         samplingPercent: double (Required)
+     *         maxRequestRate: double (Required)
+     *     }
+     *     redactionConfiguration (Optional): {
+     *         redactScoreProperties: Boolean (Optional)
+     *     }
+     *     appInsightsConnectionString: String (Required)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     status: String (Required)
+     *     error: String (Optional)
+     *     result (Optional): [
+     *          (Optional){
+     *             evaluator: String (Required)
+     *             evaluatorId: String (Required)
+     *             score: double (Required)
+     *             status: String (Required)
+     *             reason: String (Optional)
+     *             version: String (Optional)
+     *             threadId: String (Optional)
+     *             runId: String (Required)
+     *             error: String (Optional)
+     *             additionalDetails (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param evaluation Agent evaluation to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return evaluation response for agent evaluation run along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createAgentEvaluationWithResponseAsync(BinaryData evaluation, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.createAgentEvaluation(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), contentType, accept, evaluation, requestOptions, context)); + } + + /** + * Creates an agent evaluation run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     runId: String (Required)
+     *     threadId: String (Optional)
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     *     samplingConfiguration (Optional): {
+     *         name: String (Required)
+     *         samplingPercent: double (Required)
+     *         maxRequestRate: double (Required)
+     *     }
+     *     redactionConfiguration (Optional): {
+     *         redactScoreProperties: Boolean (Optional)
+     *     }
+     *     appInsightsConnectionString: String (Required)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     status: String (Required)
+     *     error: String (Optional)
+     *     result (Optional): [
+     *          (Optional){
+     *             evaluator: String (Required)
+     *             evaluatorId: String (Required)
+     *             score: double (Required)
+     *             status: String (Required)
+     *             reason: String (Optional)
+     *             version: String (Optional)
+     *             threadId: String (Optional)
+     *             runId: String (Required)
+     *             error: String (Optional)
+     *             additionalDetails (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param evaluation Agent evaluation to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return evaluation response for agent evaluation run along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createAgentEvaluationWithResponse(BinaryData evaluation, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createAgentEvaluationSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), contentType, accept, evaluation, requestOptions, + Context.NONE); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Evaluation items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listEvaluationsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listEvaluationsNext(nextLink, this.client.getEndpoint(), accept, + requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     data (Required): {
+     *         type: String (Required)
+     *     }
+     *     displayName: String (Optional)
+     *     description: String (Optional)
+     *     status: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     evaluators (Required): {
+     *         String (Required): {
+     *             id: String (Required)
+     *             initParams (Optional): {
+     *                 String: BinaryData (Required)
+     *             }
+     *             dataMapping (Optional): {
+     *                 String: String (Required)
+     *             }
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Evaluation items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listEvaluationsNextSinglePage(String nextLink, RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listEvaluationsNextSync(nextLink, this.client.getEndpoint(), accept, + requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/IndexesImpl.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/IndexesImpl.java new file mode 100644 index 000000000000..ad9989ddb914 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/IndexesImpl.java @@ -0,0 +1,911 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.projects.implementation; + +import com.azure.ai.projects.ProjectsServiceVersion; +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.Delete; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.Patch; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in Indexes. + */ +public final class IndexesImpl { + /** + * The proxy service used to perform REST calls. + */ + private final IndexesService service; + + /** + * The service client containing this operation class. + */ + private final AIProjectClientImpl client; + + /** + * Initializes an instance of IndexesImpl. + * + * @param client the instance of the service client containing this operation class. + */ + IndexesImpl(AIProjectClientImpl client) { + this.service = RestProxy.create(IndexesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public ProjectsServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for AIProjectClientIndexes to be used by the proxy service to perform + * REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "AIProjectClientIndex") + public interface IndexesService { + @Get("/indexes/{name}/versions") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listIndexVersions(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/indexes/{name}/versions") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listIndexVersionsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/indexes") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listLatestIndexVersions(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/indexes") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listLatestIndexVersionsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/indexes/{name}/versions/{version}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getIndexVersion(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Get("/indexes/{name}/versions/{version}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getIndexVersionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Delete("/indexes/{name}/versions/{version}") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> deleteIndexVersion(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Delete("/indexes/{name}/versions/{version}") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteIndexVersionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @PathParam("version") String version, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Patch("/indexes/{name}/versions/{version}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createOrUpdateIndexVersion(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Content-Type") String contentType, @PathParam("version") String version, + @HeaderParam("Accept") String accept, @BodyParam("application/merge-patch+json") BinaryData body, + RequestOptions requestOptions, Context context); + + @Patch("/indexes/{name}/versions/{version}") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createOrUpdateIndexVersionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Content-Type") String contentType, @PathParam("version") String version, + @HeaderParam("Accept") String accept, @BodyParam("application/merge-patch+json") BinaryData body, + RequestOptions requestOptions, Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listIndexVersionsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listIndexVersionsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listLatestIndexVersionsNext( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listLatestIndexVersionsNextSync( + @PathParam(value = "nextLink", encoded = true) String nextLink, @HostParam("endpoint") String endpoint, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + } + + /** + * List all versions of the given Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listIndexVersionsSinglePageAsync(String name, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listIndexVersions(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * List all versions of the given Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listIndexVersionsAsync(String name, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> listIndexVersionsSinglePageAsync(name, requestOptions), + nextLink -> listIndexVersionsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); + } + + /** + * List all versions of the given Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listIndexVersionsSinglePage(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listIndexVersionsSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + /** + * List all versions of the given Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listIndexVersions(String name, RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> listIndexVersionsSinglePage(name, requestOptions), + nextLink -> listIndexVersionsNextSinglePage(nextLink, requestOptionsForNextPage)); + } + + /** + * List the latest version of each Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listLatestIndexVersionsSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listLatestIndexVersions(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * List the latest version of each Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listLatestIndexVersionsAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> listLatestIndexVersionsSinglePageAsync(requestOptions), + nextLink -> listLatestIndexVersionsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); + } + + /** + * List the latest version of each Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listLatestIndexVersionsSinglePage(RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listLatestIndexVersionsSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + /** + * List the latest version of each Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listLatestIndexVersions(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> listLatestIndexVersionsSinglePage(requestOptions), + nextLink -> listLatestIndexVersionsNextSinglePage(nextLink, requestOptionsForNextPage)); + } + + /** + * Get the specific version of the Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the Index to retrieve. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the specific version of the Index along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getIndexVersionWithResponseAsync(String name, String version, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getIndexVersion(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, version, accept, requestOptions, context)); + } + + /** + * Get the specific version of the Index. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the Index to retrieve. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the specific version of the Index along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getIndexVersionWithResponse(String name, String version, + RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getIndexVersionSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + name, version, accept, requestOptions, Context.NONE); + } + + /** + * Delete the specific version of the Index. + * + * @param name The name of the resource. + * @param version The version of the Index to delete. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteIndexVersionWithResponseAsync(String name, String version, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.deleteIndexVersion(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, version, accept, requestOptions, context)); + } + + /** + * Delete the specific version of the Index. + * + * @param name The name of the resource. + * @param version The version of the Index to delete. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteIndexVersionWithResponse(String name, String version, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.deleteIndexVersionSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + name, version, accept, requestOptions, Context.NONE); + } + + /** + * Create a new or update an existing Index with the given version id. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the Index to create or replace. + * @param body The definition of the Index to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return index resource Definition along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateIndexVersionWithResponseAsync(String name, String version, + BinaryData body, RequestOptions requestOptions) { + final String contentType = "application/merge-patch+json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.createOrUpdateIndexVersion(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, contentType, version, accept, body, requestOptions, + context)); + } + + /** + * Create a new or update an existing Index with the given version id. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the resource. + * @param version The specific version id of the Index to create or replace. + * @param body The definition of the Index to create or update. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return index resource Definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateIndexVersionWithResponse(String name, String version, BinaryData body, + RequestOptions requestOptions) { + final String contentType = "application/merge-patch+json"; + final String accept = "application/json"; + return service.createOrUpdateIndexVersionSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, contentType, version, accept, body, requestOptions, + Context.NONE); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listIndexVersionsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listIndexVersionsNext(nextLink, this.client.getEndpoint(), accept, + requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listIndexVersionsNextSinglePage(String nextLink, RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listIndexVersionsNextSync(nextLink, this.client.getEndpoint(), accept, + requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listLatestIndexVersionsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listLatestIndexVersionsNext(nextLink, this.client.getEndpoint(), accept, + requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     type: String(AzureSearch/CosmosDBNoSqlVectorStore/ManagedAzureSearch) (Required)
+     *     id: String (Optional)
+     *     name: String (Required)
+     *     version: String (Required)
+     *     description: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of Index items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listLatestIndexVersionsNextSinglePage(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listLatestIndexVersionsNextSync(nextLink, this.client.getEndpoint(), accept, + requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/JsonMergePatchHelper.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/JsonMergePatchHelper.java new file mode 100644 index 000000000000..88f126cae67a --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/JsonMergePatchHelper.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.projects.implementation; + +import com.azure.ai.projects.models.DatasetVersion; +import com.azure.ai.projects.models.EmbeddingConfiguration; +import com.azure.ai.projects.models.FieldMapping; +import com.azure.ai.projects.models.Index; +import java.util.Map; + +/** + * This is the Helper class to enable json merge patch serialization for a model. + */ +public class JsonMergePatchHelper { + private static DatasetVersionAccessor datasetVersionAccessor; + + public interface DatasetVersionAccessor { + DatasetVersion prepareModelForJsonMergePatch(DatasetVersion datasetVersion, boolean jsonMergePatchEnabled); + + boolean isJsonMergePatch(DatasetVersion datasetVersion); + + void setDataUri(DatasetVersion datasetVersion, String dataUri); + + void setIsReference(DatasetVersion datasetVersion, Boolean isReference); + + void setConnectionName(DatasetVersion datasetVersion, String connectionName); + + void setId(DatasetVersion datasetVersion, String id); + + void setName(DatasetVersion datasetVersion, String name); + + void setVersion(DatasetVersion datasetVersion, String version); + + void setDescription(DatasetVersion datasetVersion, String description); + + void setTags(DatasetVersion datasetVersion, Map tags); + } + + public static void setDatasetVersionAccessor(DatasetVersionAccessor accessor) { + datasetVersionAccessor = accessor; + } + + public static DatasetVersionAccessor getDatasetVersionAccessor() { + return datasetVersionAccessor; + } + + private static IndexAccessor indexAccessor; + + public interface IndexAccessor { + Index prepareModelForJsonMergePatch(Index index, boolean jsonMergePatchEnabled); + + boolean isJsonMergePatch(Index index); + + void setId(Index index, String id); + + void setName(Index index, String name); + + void setVersion(Index index, String version); + + void setDescription(Index index, String description); + + void setTags(Index index, Map tags); + } + + public static void setIndexAccessor(IndexAccessor accessor) { + indexAccessor = accessor; + } + + public static IndexAccessor getIndexAccessor() { + return indexAccessor; + } + + private static FieldMappingAccessor fieldMappingAccessor; + + public interface FieldMappingAccessor { + FieldMapping prepareModelForJsonMergePatch(FieldMapping fieldMapping, boolean jsonMergePatchEnabled); + + boolean isJsonMergePatch(FieldMapping fieldMapping); + } + + public static void setFieldMappingAccessor(FieldMappingAccessor accessor) { + fieldMappingAccessor = accessor; + } + + public static FieldMappingAccessor getFieldMappingAccessor() { + return fieldMappingAccessor; + } + + private static EmbeddingConfigurationAccessor embeddingConfigurationAccessor; + + public interface EmbeddingConfigurationAccessor { + EmbeddingConfiguration prepareModelForJsonMergePatch(EmbeddingConfiguration embeddingConfiguration, + boolean jsonMergePatchEnabled); + + boolean isJsonMergePatch(EmbeddingConfiguration embeddingConfiguration); + } + + public static void setEmbeddingConfigurationAccessor(EmbeddingConfigurationAccessor accessor) { + embeddingConfigurationAccessor = accessor; + } + + public static EmbeddingConfigurationAccessor getEmbeddingConfigurationAccessor() { + return embeddingConfigurationAccessor; + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/RedTeamsImpl.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/RedTeamsImpl.java new file mode 100644 index 000000000000..ace3df971ef3 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/RedTeamsImpl.java @@ -0,0 +1,726 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.projects.implementation; + +import com.azure.ai.projects.ProjectsServiceVersion; +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.exception.ResourceModifiedException; +import com.azure.core.exception.ResourceNotFoundException; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedResponseBase; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in RedTeams. + */ +public final class RedTeamsImpl { + /** + * The proxy service used to perform REST calls. + */ + private final RedTeamsService service; + + /** + * The service client containing this operation class. + */ + private final AIProjectClientImpl client; + + /** + * Initializes an instance of RedTeamsImpl. + * + * @param client the instance of the service client containing this operation class. + */ + RedTeamsImpl(AIProjectClientImpl client) { + this.service = RestProxy.create(RedTeamsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * Gets Service version. + * + * @return the serviceVersion value. + */ + public ProjectsServiceVersion getServiceVersion() { + return client.getServiceVersion(); + } + + /** + * The interface defining all the services for AIProjectClientRedTeams to be used by the proxy service to perform + * REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "AIProjectClientRedTe") + public interface RedTeamsService { + @Get("/redTeams/runs/{name}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getRedTeam(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/redTeams/runs/{name}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getRedTeamSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @PathParam("name") String name, + @HeaderParam("Accept") String accept, RequestOptions requestOptions, Context context); + + @Get("/redTeams/runs") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listRedTeams(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/redTeams/runs") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listRedTeamsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/redTeams/runs:run") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createRedTeam(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData redTeam, + RequestOptions requestOptions, Context context); + + @Post("/redTeams/runs:run") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createRedTeamSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Content-Type") String contentType, + @HeaderParam("Accept") String accept, @BodyParam("application/json") BinaryData redTeam, + RequestOptions requestOptions, Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listRedTeamsNext(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + + @Get("{nextLink}") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listRedTeamsNextSync(@PathParam(value = "nextLink", encoded = true) String nextLink, + @HostParam("endpoint") String endpoint, @HeaderParam("Accept") String accept, RequestOptions requestOptions, + Context context); + } + + /** + * Get a redteam by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name Identifier of the red team run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a redteam by name along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getRedTeamWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getRedTeam(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), name, accept, requestOptions, context)); + } + + /** + * Get a redteam by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name Identifier of the red team run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return a redteam by name along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getRedTeamWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json"; + return service.getRedTeamSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), name, + accept, requestOptions, Context.NONE); + } + + /** + * List a redteam by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of RedTeam items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listRedTeamsSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil + .withContext(context -> service.listRedTeams(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * List a redteam by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of RedTeam items as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listRedTeamsAsync(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedFlux<>(() -> listRedTeamsSinglePageAsync(requestOptions), + nextLink -> listRedTeamsNextSinglePageAsync(nextLink, requestOptionsForNextPage)); + } + + /** + * List a redteam by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of RedTeam items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listRedTeamsSinglePage(RequestOptions requestOptions) { + final String accept = "application/json"; + Response res = service.listRedTeamsSync(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + /** + * List a redteam by name. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of RedTeam items as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listRedTeams(RequestOptions requestOptions) { + RequestOptions requestOptionsForNextPage = new RequestOptions(); + requestOptionsForNextPage.setContext( + requestOptions != null && requestOptions.getContext() != null ? requestOptions.getContext() : Context.NONE); + return new PagedIterable<>(() -> listRedTeamsSinglePage(requestOptions), + nextLink -> listRedTeamsNextSinglePage(nextLink, requestOptionsForNextPage)); + } + + /** + * Creates a redteam run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param redTeam Redteam to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return red team details along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createRedTeamWithResponseAsync(BinaryData redTeam, + RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.createRedTeam(this.client.getEndpoint(), + this.client.getServiceVersion().getVersion(), contentType, accept, redTeam, requestOptions, context)); + } + + /** + * Creates a redteam run. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param redTeam Redteam to be run. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return red team details along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createRedTeamWithResponse(BinaryData redTeam, RequestOptions requestOptions) { + final String contentType = "application/json"; + final String accept = "application/json"; + return service.createRedTeamSync(this.client.getEndpoint(), this.client.getServiceVersion().getVersion(), + contentType, accept, redTeam, requestOptions, Context.NONE); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of RedTeam items along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listRedTeamsNextSinglePageAsync(String nextLink, + RequestOptions requestOptions) { + final String accept = "application/json"; + return FluxUtil.withContext( + context -> service.listRedTeamsNext(nextLink, this.client.getEndpoint(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); + } + + /** + * Get the next page of items. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     id: String (Required)
+     *     displayName: String (Optional)
+     *     numTurns: Integer (Optional)
+     *     attackStrategies (Optional): [
+     *         String(easy/moderate/difficult/ascii_art/ascii_smuggler/atbash/base64/binary/caesar/character_space/jailbreak/ansii_attack/character_swap/suffix_append/string_join/unicode_confusable/unicode_substitution/diacritic/flip/leetspeak/rot13/morse/url/baseline) (Optional)
+     *     ]
+     *     simulationOnly: Boolean (Optional)
+     *     riskCategories (Optional): [
+     *         String(HateUnfairness/Violence/Sexual/SelfHarm) (Optional)
+     *     ]
+     *     applicationScenario: String (Optional)
+     *     tags (Optional): {
+     *         String: String (Required)
+     *     }
+     *     properties (Optional): {
+     *         String: String (Required)
+     *     }
+     *     status: String (Optional)
+     *     target (Required): {
+     *         type: String (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param nextLink The URL to get the next list of items. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. + * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. + * @return paged collection of RedTeam items along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listRedTeamsNextSinglePage(String nextLink, RequestOptions requestOptions) { + final String accept = "application/json"; + Response res + = service.listRedTeamsNextSync(nextLink, this.client.getEndpoint(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); + } + + private List getValues(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + List values = (List) obj.get(path); + return values.stream().map(BinaryData::fromObject).collect(Collectors.toList()); + } catch (RuntimeException e) { + return null; + } + } + + private String getNextLink(BinaryData binaryData, String path) { + try { + Map obj = binaryData.toObject(Map.class); + return (String) obj.get(path); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/package-info.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/package-info.java new file mode 100644 index 000000000000..09f9fb8c7506 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/implementation/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +/** + * + * Package containing the implementations for Projects. + * + */ +package com.azure.ai.projects.implementation; diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluation.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluation.java new file mode 100644 index 000000000000..858c74a7ef90 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluation.java @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.List; + +/** + * Evaluation response for agent evaluation run. + */ +@Immutable +public final class AgentEvaluation implements JsonSerializable { + + /* + * Identifier of the agent evaluation run. + */ + @Generated + private final String id; + + /* + * Status of the agent evaluation. Options: Running, Completed, Failed. + */ + @Generated + private final String status; + + /* + * The reason of the request failure for the long running process, if applicable. + */ + @Generated + private String error; + + /* + * The agent evaluation result. + */ + @Generated + private List result; + + /** + * Creates an instance of AgentEvaluation class. + * + * @param id the id value to set. + * @param status the status value to set. + */ + @Generated + private AgentEvaluation(String id, String status) { + this.id = id; + this.status = status; + } + + /** + * Get the id property: Identifier of the agent evaluation run. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the status property: Status of the agent evaluation. Options: Running, Completed, Failed. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the error property: The reason of the request failure for the long running process, if applicable. + * + * @return the error value. + */ + @Generated + public String getError() { + return this.error; + } + + /** + * Get the result property: The agent evaluation result. + * + * @return the result value. + */ + @Generated + public List getResult() { + return this.result; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("error", this.error); + jsonWriter.writeArrayField("result", this.result, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AgentEvaluation from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AgentEvaluation if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the AgentEvaluation. + */ + @Generated + public static AgentEvaluation fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String status = null; + String error = null; + List result = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("error".equals(fieldName)) { + error = reader.getString(); + } else if ("result".equals(fieldName)) { + result = reader.readArray(reader1 -> AgentEvaluationResult.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + AgentEvaluation deserializedAgentEvaluation = new AgentEvaluation(id, status); + deserializedAgentEvaluation.error = error; + deserializedAgentEvaluation.result = result; + return deserializedAgentEvaluation; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationRedactionConfiguration.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationRedactionConfiguration.java new file mode 100644 index 000000000000..ee4d8f017649 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationRedactionConfiguration.java @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * The redaction configuration will allow the user to control what is redacted. + */ +@Fluent +public final class AgentEvaluationRedactionConfiguration + implements JsonSerializable { + + /* + * Redact score properties. If not specified, the default is to redact in production. + */ + @Generated + private Boolean redactScoreProperties; + + /** + * Creates an instance of AgentEvaluationRedactionConfiguration class. + */ + @Generated + public AgentEvaluationRedactionConfiguration() { + } + + /** + * Get the redactScoreProperties property: Redact score properties. If not specified, the default is to redact in + * production. + * + * @return the redactScoreProperties value. + */ + @Generated + public Boolean isRedactScoreProperties() { + return this.redactScoreProperties; + } + + /** + * Set the redactScoreProperties property: Redact score properties. If not specified, the default is to redact in + * production. + * + * @param redactScoreProperties the redactScoreProperties value to set. + * @return the AgentEvaluationRedactionConfiguration object itself. + */ + @Generated + public AgentEvaluationRedactionConfiguration setRedactScoreProperties(Boolean redactScoreProperties) { + this.redactScoreProperties = redactScoreProperties; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("redactScoreProperties", this.redactScoreProperties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AgentEvaluationRedactionConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AgentEvaluationRedactionConfiguration if the JsonReader was pointing to an instance of it, + * or null if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the AgentEvaluationRedactionConfiguration. + */ + @Generated + public static AgentEvaluationRedactionConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AgentEvaluationRedactionConfiguration deserializedAgentEvaluationRedactionConfiguration + = new AgentEvaluationRedactionConfiguration(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("redactScoreProperties".equals(fieldName)) { + deserializedAgentEvaluationRedactionConfiguration.redactScoreProperties + = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + return deserializedAgentEvaluationRedactionConfiguration; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationRequest.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationRequest.java new file mode 100644 index 000000000000..d65897002844 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationRequest.java @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.Map; + +/** + * Evaluation request for agent run. + */ +@Fluent +public final class AgentEvaluationRequest implements JsonSerializable { + + /* + * Identifier of the agent run. + */ + @Generated + private final String runId; + + /* + * Identifier of the agent thread. This field is mandatory currently, but it will be optional in the future. + */ + @Generated + private String threadId; + + /* + * Evaluators to be used for the evaluation. + */ + @Generated + private final Map evaluators; + + /* + * Sampling configuration for the evaluation. + */ + @Generated + private AgentEvaluationSamplingConfiguration samplingConfiguration; + + /* + * Redaction configuration for the evaluation. + */ + @Generated + private AgentEvaluationRedactionConfiguration redactionConfiguration; + + /* + * Pass the AppInsights connection string to the agent evaluation for the evaluation results and the errors logs. + */ + @Generated + private final String appInsightsConnectionString; + + /** + * Creates an instance of AgentEvaluationRequest class. + * + * @param runId the runId value to set. + * @param evaluators the evaluators value to set. + * @param appInsightsConnectionString the appInsightsConnectionString value to set. + */ + @Generated + public AgentEvaluationRequest(String runId, Map evaluators, + String appInsightsConnectionString) { + this.runId = runId; + this.evaluators = evaluators; + this.appInsightsConnectionString = appInsightsConnectionString; + } + + /** + * Get the runId property: Identifier of the agent run. + * + * @return the runId value. + */ + @Generated + public String getRunId() { + return this.runId; + } + + /** + * Get the threadId property: Identifier of the agent thread. This field is mandatory currently, but it will be + * optional in the future. + * + * @return the threadId value. + */ + @Generated + public String getThreadId() { + return this.threadId; + } + + /** + * Set the threadId property: Identifier of the agent thread. This field is mandatory currently, but it will be + * optional in the future. + * + * @param threadId the threadId value to set. + * @return the AgentEvaluationRequest object itself. + */ + @Generated + public AgentEvaluationRequest setThreadId(String threadId) { + this.threadId = threadId; + return this; + } + + /** + * Get the evaluators property: Evaluators to be used for the evaluation. + * + * @return the evaluators value. + */ + @Generated + public Map getEvaluators() { + return this.evaluators; + } + + /** + * Get the samplingConfiguration property: Sampling configuration for the evaluation. + * + * @return the samplingConfiguration value. + */ + @Generated + public AgentEvaluationSamplingConfiguration getSamplingConfiguration() { + return this.samplingConfiguration; + } + + /** + * Set the samplingConfiguration property: Sampling configuration for the evaluation. + * + * @param samplingConfiguration the samplingConfiguration value to set. + * @return the AgentEvaluationRequest object itself. + */ + @Generated + public AgentEvaluationRequest setSamplingConfiguration(AgentEvaluationSamplingConfiguration samplingConfiguration) { + this.samplingConfiguration = samplingConfiguration; + return this; + } + + /** + * Get the redactionConfiguration property: Redaction configuration for the evaluation. + * + * @return the redactionConfiguration value. + */ + @Generated + public AgentEvaluationRedactionConfiguration getRedactionConfiguration() { + return this.redactionConfiguration; + } + + /** + * Set the redactionConfiguration property: Redaction configuration for the evaluation. + * + * @param redactionConfiguration the redactionConfiguration value to set. + * @return the AgentEvaluationRequest object itself. + */ + @Generated + public AgentEvaluationRequest + setRedactionConfiguration(AgentEvaluationRedactionConfiguration redactionConfiguration) { + this.redactionConfiguration = redactionConfiguration; + return this; + } + + /** + * Get the appInsightsConnectionString property: Pass the AppInsights connection string to the agent evaluation for + * the evaluation results and the errors logs. + * + * @return the appInsightsConnectionString value. + */ + @Generated + public String getAppInsightsConnectionString() { + return this.appInsightsConnectionString; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("runId", this.runId); + jsonWriter.writeMapField("evaluators", this.evaluators, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("appInsightsConnectionString", this.appInsightsConnectionString); + jsonWriter.writeStringField("threadId", this.threadId); + jsonWriter.writeJsonField("samplingConfiguration", this.samplingConfiguration); + jsonWriter.writeJsonField("redactionConfiguration", this.redactionConfiguration); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AgentEvaluationRequest from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AgentEvaluationRequest if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the AgentEvaluationRequest. + */ + @Generated + public static AgentEvaluationRequest fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String runId = null; + Map evaluators = null; + String appInsightsConnectionString = null; + String threadId = null; + AgentEvaluationSamplingConfiguration samplingConfiguration = null; + AgentEvaluationRedactionConfiguration redactionConfiguration = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("runId".equals(fieldName)) { + runId = reader.getString(); + } else if ("evaluators".equals(fieldName)) { + evaluators = reader.readMap(reader1 -> EvaluatorConfiguration.fromJson(reader1)); + } else if ("appInsightsConnectionString".equals(fieldName)) { + appInsightsConnectionString = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("samplingConfiguration".equals(fieldName)) { + samplingConfiguration = AgentEvaluationSamplingConfiguration.fromJson(reader); + } else if ("redactionConfiguration".equals(fieldName)) { + redactionConfiguration = AgentEvaluationRedactionConfiguration.fromJson(reader); + } else { + reader.skipChildren(); + } + } + AgentEvaluationRequest deserializedAgentEvaluationRequest + = new AgentEvaluationRequest(runId, evaluators, appInsightsConnectionString); + deserializedAgentEvaluationRequest.threadId = threadId; + deserializedAgentEvaluationRequest.samplingConfiguration = samplingConfiguration; + deserializedAgentEvaluationRequest.redactionConfiguration = redactionConfiguration; + return deserializedAgentEvaluationRequest; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationResult.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationResult.java new file mode 100644 index 000000000000..87ef31bd5e54 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationResult.java @@ -0,0 +1,281 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.Map; + +/** + * Result for the agent evaluation evaluator run. + */ +@Immutable +public final class AgentEvaluationResult implements JsonSerializable { + + /* + * Evaluator's name. This is the name of the evaluator that was used to evaluate the agent's completion. + */ + @Generated + private final String evaluator; + + /* + * Identifier of the evaluator. + */ + @Generated + private final String evaluatorId; + + /* + * Score of the given evaluator. No restriction on range. + */ + @Generated + private final double score; + + /* + * Status of the evaluator result. Options: Running, Completed, Failed, NotApplicable. + */ + @Generated + private final String status; + + /* + * Reasoning for the evaluation result. + */ + @Generated + private String reason; + + /* + * Version of the evaluator that was used to evaluate the agent's completion. + */ + @Generated + private String version; + + /* + * The unique identifier of the thread. + */ + @Generated + private String threadId; + + /* + * The unique identifier of the run. + */ + @Generated + private final String runId; + + /* + * A string explaining why there was an error, if applicable. + */ + @Generated + private String error; + + /* + * Additional properties relevant to the evaluator. These will differ between evaluators. + */ + @Generated + private Map additionalDetails; + + /** + * Creates an instance of AgentEvaluationResult class. + * + * @param evaluator the evaluator value to set. + * @param evaluatorId the evaluatorId value to set. + * @param score the score value to set. + * @param status the status value to set. + * @param runId the runId value to set. + */ + @Generated + private AgentEvaluationResult(String evaluator, String evaluatorId, double score, String status, String runId) { + this.evaluator = evaluator; + this.evaluatorId = evaluatorId; + this.score = score; + this.status = status; + this.runId = runId; + } + + /** + * Get the evaluator property: Evaluator's name. This is the name of the evaluator that was used to evaluate the + * agent's completion. + * + * @return the evaluator value. + */ + @Generated + public String getEvaluator() { + return this.evaluator; + } + + /** + * Get the evaluatorId property: Identifier of the evaluator. + * + * @return the evaluatorId value. + */ + @Generated + public String getEvaluatorId() { + return this.evaluatorId; + } + + /** + * Get the score property: Score of the given evaluator. No restriction on range. + * + * @return the score value. + */ + @Generated + public double getScore() { + return this.score; + } + + /** + * Get the status property: Status of the evaluator result. Options: Running, Completed, Failed, NotApplicable. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the reason property: Reasoning for the evaluation result. + * + * @return the reason value. + */ + @Generated + public String getReason() { + return this.reason; + } + + /** + * Get the version property: Version of the evaluator that was used to evaluate the agent's completion. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the threadId property: The unique identifier of the thread. + * + * @return the threadId value. + */ + @Generated + public String getThreadId() { + return this.threadId; + } + + /** + * Get the runId property: The unique identifier of the run. + * + * @return the runId value. + */ + @Generated + public String getRunId() { + return this.runId; + } + + /** + * Get the error property: A string explaining why there was an error, if applicable. + * + * @return the error value. + */ + @Generated + public String getError() { + return this.error; + } + + /** + * Get the additionalDetails property: Additional properties relevant to the evaluator. These will differ between + * evaluators. + * + * @return the additionalDetails value. + */ + @Generated + public Map getAdditionalDetails() { + return this.additionalDetails; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("evaluator", this.evaluator); + jsonWriter.writeStringField("evaluatorId", this.evaluatorId); + jsonWriter.writeDoubleField("score", this.score); + jsonWriter.writeStringField("status", this.status); + jsonWriter.writeStringField("runId", this.runId); + jsonWriter.writeStringField("reason", this.reason); + jsonWriter.writeStringField("version", this.version); + jsonWriter.writeStringField("threadId", this.threadId); + jsonWriter.writeStringField("error", this.error); + jsonWriter.writeMapField("additionalDetails", this.additionalDetails, + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AgentEvaluationResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AgentEvaluationResult if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the AgentEvaluationResult. + */ + @Generated + public static AgentEvaluationResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String evaluator = null; + String evaluatorId = null; + double score = 0.0; + String status = null; + String runId = null; + String reason = null; + String version = null; + String threadId = null; + String error = null; + Map additionalDetails = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("evaluator".equals(fieldName)) { + evaluator = reader.getString(); + } else if ("evaluatorId".equals(fieldName)) { + evaluatorId = reader.getString(); + } else if ("score".equals(fieldName)) { + score = reader.getDouble(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("runId".equals(fieldName)) { + runId = reader.getString(); + } else if ("reason".equals(fieldName)) { + reason = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getString(); + } else if ("threadId".equals(fieldName)) { + threadId = reader.getString(); + } else if ("error".equals(fieldName)) { + error = reader.getString(); + } else if ("additionalDetails".equals(fieldName)) { + additionalDetails = reader.readMap(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + AgentEvaluationResult deserializedAgentEvaluationResult + = new AgentEvaluationResult(evaluator, evaluatorId, score, status, runId); + deserializedAgentEvaluationResult.reason = reason; + deserializedAgentEvaluationResult.version = version; + deserializedAgentEvaluationResult.threadId = threadId; + deserializedAgentEvaluationResult.error = error; + deserializedAgentEvaluationResult.additionalDetails = additionalDetails; + return deserializedAgentEvaluationResult; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationSamplingConfiguration.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationSamplingConfiguration.java new file mode 100644 index 000000000000..a364e640fa3b --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AgentEvaluationSamplingConfiguration.java @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Definition for sampling strategy. + */ +@Immutable +public final class AgentEvaluationSamplingConfiguration + implements JsonSerializable { + + /* + * Name of the sampling strategy. + */ + @Generated + private final String name; + + /* + * Percentage of sampling per hour (0-100). + */ + @Generated + private final double samplingPercent; + + /* + * Maximum request rate per hour (0 to 1000). + */ + @Generated + private final double maxRequestRate; + + /** + * Creates an instance of AgentEvaluationSamplingConfiguration class. + * + * @param name the name value to set. + * @param samplingPercent the samplingPercent value to set. + * @param maxRequestRate the maxRequestRate value to set. + */ + @Generated + public AgentEvaluationSamplingConfiguration(String name, double samplingPercent, double maxRequestRate) { + this.name = name; + this.samplingPercent = samplingPercent; + this.maxRequestRate = maxRequestRate; + } + + /** + * Get the name property: Name of the sampling strategy. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the samplingPercent property: Percentage of sampling per hour (0-100). + * + * @return the samplingPercent value. + */ + @Generated + public double getSamplingPercent() { + return this.samplingPercent; + } + + /** + * Get the maxRequestRate property: Maximum request rate per hour (0 to 1000). + * + * @return the maxRequestRate value. + */ + @Generated + public double getMaxRequestRate() { + return this.maxRequestRate; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeDoubleField("samplingPercent", this.samplingPercent); + jsonWriter.writeDoubleField("maxRequestRate", this.maxRequestRate); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AgentEvaluationSamplingConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AgentEvaluationSamplingConfiguration if the JsonReader was pointing to an instance of it, + * or null if it was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the AgentEvaluationSamplingConfiguration. + */ + @Generated + public static AgentEvaluationSamplingConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + double samplingPercent = 0.0; + double maxRequestRate = 0.0; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("samplingPercent".equals(fieldName)) { + samplingPercent = reader.getDouble(); + } else if ("maxRequestRate".equals(fieldName)) { + maxRequestRate = reader.getDouble(); + } else { + reader.skipChildren(); + } + } + return new AgentEvaluationSamplingConfiguration(name, samplingPercent, maxRequestRate); + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ApiKeyCredentials.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ApiKeyCredentials.java new file mode 100644 index 000000000000..d824796ccaf0 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ApiKeyCredentials.java @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * API Key Credential definition. + */ +@Immutable +public final class ApiKeyCredentials extends BaseCredentials { + + /* + * The type of credential used by the connection + */ + @Generated + private CredentialType type = CredentialType.API_KEY; + + /* + * API Key + */ + @Generated + private String apiKey; + + /** + * Creates an instance of ApiKeyCredentials class. + */ + @Generated + private ApiKeyCredentials() { + } + + /** + * Get the type property: The type of credential used by the connection. + * + * @return the type value. + */ + @Generated + @Override + public CredentialType getType() { + return this.type; + } + + /** + * Get the apiKey property: API Key. + * + * @return the apiKey value. + */ + @Generated + public String getApiKey() { + return this.apiKey; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ApiKeyCredentials from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ApiKeyCredentials if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the ApiKeyCredentials. + */ + @Generated + public static ApiKeyCredentials fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ApiKeyCredentials deserializedApiKeyCredentials = new ApiKeyCredentials(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedApiKeyCredentials.type = CredentialType.fromString(reader.getString()); + } else if ("key".equals(fieldName)) { + deserializedApiKeyCredentials.apiKey = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedApiKeyCredentials; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AssetCredentialResponse.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AssetCredentialResponse.java new file mode 100644 index 000000000000..dbf257cbef49 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AssetCredentialResponse.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Represents a reference to a blob for consumption. + */ +@Immutable +public final class AssetCredentialResponse implements JsonSerializable { + + /* + * Credential info to access the storage account. + */ + @Generated + private final BlobReference blobReference; + + /** + * Creates an instance of AssetCredentialResponse class. + * + * @param blobReference the blobReference value to set. + */ + @Generated + private AssetCredentialResponse(BlobReference blobReference) { + this.blobReference = blobReference; + } + + /** + * Get the blobReference property: Credential info to access the storage account. + * + * @return the blobReference value. + */ + @Generated + public BlobReference getBlobReference() { + return this.blobReference; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("blobReference", this.blobReference); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssetCredentialResponse from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssetCredentialResponse if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the AssetCredentialResponse. + */ + @Generated + public static AssetCredentialResponse fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + BlobReference blobReference = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("blobReference".equals(fieldName)) { + blobReference = BlobReference.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new AssetCredentialResponse(blobReference); + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AssetCredentialResult.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AssetCredentialResult.java new file mode 100644 index 000000000000..8e817ec61699 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AssetCredentialResult.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Represents a reference to a blob for consumption. + */ +@Immutable +public final class AssetCredentialResult implements JsonSerializable { + + /* + * Credential info to access the storage account. + */ + @Generated + private final BlobReference blobReference; + + /** + * Creates an instance of AssetCredentialResult class. + * + * @param blobReference the blobReference value to set. + */ + @Generated + private AssetCredentialResult(BlobReference blobReference) { + this.blobReference = blobReference; + } + + /** + * Get the blobReference property: Credential info to access the storage account. + * + * @return the blobReference value. + */ + @Generated + public BlobReference getBlobReference() { + return this.blobReference; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("blobReference", this.blobReference); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AssetCredentialResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AssetCredentialResult if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the AssetCredentialResult. + */ + @Generated + public static AssetCredentialResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + BlobReference blobReference = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("blobReference".equals(fieldName)) { + blobReference = BlobReference.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new AssetCredentialResult(blobReference); + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AttackStrategy.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AttackStrategy.java new file mode 100644 index 000000000000..bae69fb46a97 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AttackStrategy.java @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Strategies for attacks. + */ +public final class AttackStrategy extends ExpandableStringEnum { + + /** + * 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. + */ + @Generated + public static final AttackStrategy EASY = fromString("easy"); + + /** + * Represents a default set of moderate complexity attacks. Moderate complexity attacks require having access to + * resources such as another generative AI model. + */ + @Generated + public static final AttackStrategy MODERATE = fromString("moderate"); + + /** + * 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. + */ + @Generated + public static final AttackStrategy DIFFICULT = fromString("difficult"); + + /** + * Generates visual art using ASCII characters, often used for creative or obfuscation purposes. + */ + @Generated + public static final AttackStrategy ASCII_ART = fromString("ascii_art"); + + /** + * Conceals data within ASCII characters, making it harder to detect. + */ + @Generated + public static final AttackStrategy ASCII_SMUGGLER = fromString("ascii_smuggler"); + + /** + * Implements the Atbash cipher, a simple substitution cipher where each letter is mapped to its reverse. + */ + @Generated + public static final AttackStrategy ATBASH = fromString("atbash"); + + /** + * Encodes binary data into a text format using Base64, commonly used for data transmission. + */ + @Generated + public static final AttackStrategy BASE64 = fromString("base64"); + + /** + * Converts text into binary code, representing data in a series of 0s and 1s. + */ + @Generated + public static final AttackStrategy BINARY = fromString("binary"); + + /** + * Applies the Caesar cipher, a substitution cipher that shifts characters by a fixed number of positions. + */ + @Generated + public static final AttackStrategy CAESAR = fromString("caesar"); + + /** + * Alters text by adding spaces between characters, often used for obfuscation. + */ + @Generated + public static final AttackStrategy CHARACTER_SPACE = fromString("character_space"); + + /** + * Injects specially crafted prompts to bypass AI safeguards, known as User Injected Prompt Attacks (UPIA). + */ + @Generated + public static final AttackStrategy JAILBREAK = fromString("jailbreak"); + + /** + * Utilizes ANSI escape sequences to manipulate text appearance and behavior. + */ + @Generated + public static final AttackStrategy ANSII_ATTACK = fromString("ansii_attack"); + + /** + * Swaps characters within text to create variations or obfuscate the original content. + */ + @Generated + public static final AttackStrategy CHARACTER_SWAP = fromString("character_swap"); + + /** + * Appends an adversarial suffix to the prompt. + */ + @Generated + public static final AttackStrategy SUFFIX_APPEND = fromString("suffix_append"); + + /** + * Joins multiple strings together, often used for concatenation or obfuscation. + */ + @Generated + public static final AttackStrategy STRING_JOIN = fromString("string_join"); + + /** + * Uses Unicode characters that look similar to standard characters, creating visual confusion. + */ + @Generated + public static final AttackStrategy UNICODE_CONFUSABLE = fromString("unicode_confusable"); + + /** + * Substitutes standard characters with Unicode equivalents, often for obfuscation. + */ + @Generated + public static final AttackStrategy UNICODE_SUBSTITUTION = fromString("unicode_substitution"); + + /** + * Adds diacritical marks to characters, changing their appearance and sometimes their meaning. + */ + @Generated + public static final AttackStrategy DIACRITIC = fromString("diacritic"); + + /** + * Flips characters from front to back, creating a mirrored effect. + */ + @Generated + public static final AttackStrategy FLIP = fromString("flip"); + + /** + * Transforms text into Leetspeak, a form of encoding that replaces letters with similar-looking numbers or symbols. + */ + @Generated + public static final AttackStrategy LEETSPEAK = fromString("leetspeak"); + + /** + * Applies the ROT13 cipher, a simple substitution cipher that shifts characters by 13 positions. + */ + @Generated + public static final AttackStrategy ROT13 = fromString("rot13"); + + /** + * Encodes text into Morse code, using dots and dashes to represent characters. + */ + @Generated + public static final AttackStrategy MORSE = fromString("morse"); + + /** + * Encodes text into URL format. + */ + @Generated + public static final AttackStrategy URL = fromString("url"); + + /** + * Represents the baseline direct adversarial probing, which is used by attack strategies as the attack objective. + */ + @Generated + public static final AttackStrategy BASELINE = fromString("baseline"); + + /** + * Creates a new instance of AttackStrategy value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public AttackStrategy() { + } + + /** + * Creates or finds a AttackStrategy from its string representation. + * + * @param name a name to look for. + * @return the corresponding AttackStrategy. + */ + @Generated + public static AttackStrategy fromString(String name) { + return fromString(name, AttackStrategy.class); + } + + /** + * Gets known AttackStrategy values. + * + * @return known AttackStrategy values. + */ + @Generated + public static Collection values() { + return values(AttackStrategy.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AzureAISearchIndex.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AzureAISearchIndex.java new file mode 100644 index 000000000000..e5b5492b82b7 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AzureAISearchIndex.java @@ -0,0 +1,278 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Azure AI Search Index Definition. + */ +@Fluent +public final class AzureAISearchIndex extends Index { + + /* + * Type of index + */ + @Generated + private IndexType type = IndexType.AZURE_SEARCH; + + /* + * Name of connection to Azure AI Search + */ + @Generated + private String connectionName; + + /* + * Name of index in Azure AI Search resource to attach + */ + @Generated + private String indexName; + + /* + * Field mapping configuration + */ + @Generated + private FieldMapping fieldMapping; + + /** + * Stores updated model property, the value is property name, not serialized name. + */ + @Generated + private final Set updatedProperties = new HashSet<>(); + + /** + * Creates an instance of AzureAISearchIndex class. + */ + @Generated + public AzureAISearchIndex() { + } + + /** + * Get the type property: Type of index. + * + * @return the type value. + */ + @Generated + @Override + public IndexType getType() { + return this.type; + } + + /** + * Get the connectionName property: Name of connection to Azure AI Search. + * + * @return the connectionName value. + */ + @Generated + public String getConnectionName() { + return this.connectionName; + } + + /** + * Set the connectionName property: Name of connection to Azure AI Search. + *

Required when create the resource.

+ * + * @param connectionName the connectionName value to set. + * @return the AzureAISearchIndex object itself. + */ + @Generated + public AzureAISearchIndex setConnectionName(String connectionName) { + this.connectionName = connectionName; + this.updatedProperties.add("connectionName"); + return this; + } + + /** + * Get the indexName property: Name of index in Azure AI Search resource to attach. + * + * @return the indexName value. + */ + @Generated + public String getIndexName() { + return this.indexName; + } + + /** + * Set the indexName property: Name of index in Azure AI Search resource to attach. + *

Required when create the resource.

+ * + * @param indexName the indexName value to set. + * @return the AzureAISearchIndex object itself. + */ + @Generated + public AzureAISearchIndex setIndexName(String indexName) { + this.indexName = indexName; + this.updatedProperties.add("indexName"); + return this; + } + + /** + * Get the fieldMapping property: Field mapping configuration. + * + * @return the fieldMapping value. + */ + @Generated + public FieldMapping getFieldMapping() { + return this.fieldMapping; + } + + /** + * Set the fieldMapping property: Field mapping configuration. + * + * @param fieldMapping the fieldMapping value to set. + * @return the AzureAISearchIndex object itself. + */ + @Generated + public AzureAISearchIndex setFieldMapping(FieldMapping fieldMapping) { + this.fieldMapping = fieldMapping; + this.updatedProperties.add("fieldMapping"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public AzureAISearchIndex setDescription(String description) { + super.setDescription(description); + this.updatedProperties.add("description"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public AzureAISearchIndex setTags(Map tags) { + super.setTags(tags); + this.updatedProperties.add("tags"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + if (JsonMergePatchHelper.getIndexAccessor().isJsonMergePatch(this)) { + return toJsonMergePatch(jsonWriter); + } else { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("description", getDescription()); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeStringField("connectionName", this.connectionName); + jsonWriter.writeStringField("indexName", this.indexName); + jsonWriter.writeJsonField("fieldMapping", this.fieldMapping); + return jsonWriter.writeEndObject(); + } + } + + @Generated + private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + if (updatedProperties.contains("description")) { + if (getDescription() == null) { + jsonWriter.writeNullField("description"); + } else { + jsonWriter.writeStringField("description", getDescription()); + } + } + if (updatedProperties.contains("tags")) { + if (getTags() == null) { + jsonWriter.writeNullField("tags"); + } else { + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> { + if (element != null) { + writer.writeString(element); + } else { + writer.writeNull(); + } + }); + } + } + jsonWriter.writeStringField("type", this.type.toString()); + if (updatedProperties.contains("connectionName")) { + if (this.connectionName == null) { + jsonWriter.writeNullField("connectionName"); + } else { + jsonWriter.writeStringField("connectionName", this.connectionName); + } + } + if (updatedProperties.contains("indexName")) { + if (this.indexName == null) { + jsonWriter.writeNullField("indexName"); + } else { + jsonWriter.writeStringField("indexName", this.indexName); + } + } + if (updatedProperties.contains("fieldMapping")) { + if (this.fieldMapping == null) { + jsonWriter.writeNullField("fieldMapping"); + } else { + JsonMergePatchHelper.getFieldMappingAccessor().prepareModelForJsonMergePatch(this.fieldMapping, true); + jsonWriter.writeJsonField("fieldMapping", this.fieldMapping); + JsonMergePatchHelper.getFieldMappingAccessor().prepareModelForJsonMergePatch(this.fieldMapping, false); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureAISearchIndex from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureAISearchIndex if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the AzureAISearchIndex. + */ + @Generated + public static AzureAISearchIndex fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + AzureAISearchIndex deserializedAzureAISearchIndex = new AzureAISearchIndex(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor().setName(deserializedAzureAISearchIndex, reader.getString()); + } else if ("version".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor() + .setVersion(deserializedAzureAISearchIndex, reader.getString()); + } else if ("id".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor().setId(deserializedAzureAISearchIndex, reader.getString()); + } else if ("description".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor() + .setDescription(deserializedAzureAISearchIndex, reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + JsonMergePatchHelper.getIndexAccessor().setTags(deserializedAzureAISearchIndex, tags); + } else if ("type".equals(fieldName)) { + deserializedAzureAISearchIndex.type = IndexType.fromString(reader.getString()); + } else if ("connectionName".equals(fieldName)) { + deserializedAzureAISearchIndex.connectionName = reader.getString(); + } else if ("indexName".equals(fieldName)) { + deserializedAzureAISearchIndex.indexName = reader.getString(); + } else if ("fieldMapping".equals(fieldName)) { + deserializedAzureAISearchIndex.fieldMapping = FieldMapping.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedAzureAISearchIndex; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AzureOpenAIModelConfiguration.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AzureOpenAIModelConfiguration.java new file mode 100644 index 000000000000..f46f3f8f2de1 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/AzureOpenAIModelConfiguration.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Azure OpenAI model configuration. The API version would be selected by the service for querying the model. + */ +@Immutable +public final class AzureOpenAIModelConfiguration extends TargetConfig { + + /* + * Type of the model configuration. + */ + @Generated + private String type = "AzureOpenAIModel"; + + /* + * Deployment name for AOAI model. Example: gpt-4o if in AIServices or connection based + * `connection_name/deployment_name` (i.e. `my-aoai-connection/gpt-4o`. + */ + @Generated + private final String modelDeploymentName; + + /** + * Creates an instance of AzureOpenAIModelConfiguration class. + * + * @param modelDeploymentName the modelDeploymentName value to set. + */ + @Generated + public AzureOpenAIModelConfiguration(String modelDeploymentName) { + this.modelDeploymentName = modelDeploymentName; + } + + /** + * Get the type property: Type of the model configuration. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } + + /** + * Get the modelDeploymentName property: Deployment name for AOAI model. Example: gpt-4o if in AIServices or + * connection based `connection_name/deployment_name` (i.e. `my-aoai-connection/gpt-4o`. + * + * @return the modelDeploymentName value. + */ + @Generated + public String getModelDeploymentName() { + return this.modelDeploymentName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("modelDeploymentName", this.modelDeploymentName); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of AzureOpenAIModelConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of AzureOpenAIModelConfiguration if the JsonReader was pointing to an instance of it, or null + * if it was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the AzureOpenAIModelConfiguration. + */ + @Generated + public static AzureOpenAIModelConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String modelDeploymentName = null; + String type = "AzureOpenAIModel"; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("modelDeploymentName".equals(fieldName)) { + modelDeploymentName = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + AzureOpenAIModelConfiguration deserializedAzureOpenAIModelConfiguration + = new AzureOpenAIModelConfiguration(modelDeploymentName); + deserializedAzureOpenAIModelConfiguration.type = type; + return deserializedAzureOpenAIModelConfiguration; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/BaseCredentials.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/BaseCredentials.java new file mode 100644 index 000000000000..c627bdc91ba7 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/BaseCredentials.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * A base class for connection credentials. + */ +@Immutable +public class BaseCredentials implements JsonSerializable { + + /* + * The type of credential used by the connection + */ + @Generated + private CredentialType type = CredentialType.fromString("BaseCredentials"); + + /** + * Creates an instance of BaseCredentials class. + */ + @Generated + protected BaseCredentials() { + } + + /** + * Get the type property: The type of credential used by the connection. + * + * @return the type value. + */ + @Generated + public CredentialType getType() { + return this.type; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of BaseCredentials from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of BaseCredentials if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the BaseCredentials. + */ + @Generated + public static BaseCredentials fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("ApiKey".equals(discriminatorValue)) { + return ApiKeyCredentials.fromJson(readerToUse.reset()); + } else if ("AAD".equals(discriminatorValue)) { + return EntraIDCredentials.fromJson(readerToUse.reset()); + } else if ("CustomKeys".equals(discriminatorValue)) { + return CustomCredential.fromJson(readerToUse.reset()); + } else if ("SAS".equals(discriminatorValue)) { + return SasCredentials.fromJson(readerToUse.reset()); + } else if ("None".equals(discriminatorValue)) { + return NoAuthenticationCredentials.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static BaseCredentials fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + BaseCredentials deserializedBaseCredentials = new BaseCredentials(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedBaseCredentials.type = CredentialType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedBaseCredentials; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/BlobReference.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/BlobReference.java new file mode 100644 index 000000000000..0dd2dee54c7b --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/BlobReference.java @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Blob reference details. + */ +@Immutable +public final class BlobReference implements JsonSerializable { + + /* + * Blob URI path for client to upload data. Example: https://blob.windows.core.net/Container/Path + */ + @Generated + private final String blobUri; + + /* + * ARM ID of the storage account to use. + */ + @Generated + private final String storageAccountArmId; + + /* + * Credential info to access the storage account. + */ + @Generated + private final SasCredential credential; + + /** + * Creates an instance of BlobReference class. + * + * @param blobUri the blobUri value to set. + * @param storageAccountArmId the storageAccountArmId value to set. + * @param credential the credential value to set. + */ + @Generated + private BlobReference(String blobUri, String storageAccountArmId, SasCredential credential) { + this.blobUri = blobUri; + this.storageAccountArmId = storageAccountArmId; + this.credential = credential; + } + + /** + * Get the blobUri property: Blob URI path for client to upload data. Example: + * https://blob.windows.core.net/Container/Path. + * + * @return the blobUri value. + */ + @Generated + public String getBlobUri() { + return this.blobUri; + } + + /** + * Get the storageAccountArmId property: ARM ID of the storage account to use. + * + * @return the storageAccountArmId value. + */ + @Generated + public String getStorageAccountArmId() { + return this.storageAccountArmId; + } + + /** + * Get the credential property: Credential info to access the storage account. + * + * @return the credential value. + */ + @Generated + public SasCredential getCredential() { + return this.credential; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("blobUri", this.blobUri); + jsonWriter.writeStringField("storageAccountArmId", this.storageAccountArmId); + jsonWriter.writeJsonField("credential", this.credential); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of BlobReference from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of BlobReference if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the BlobReference. + */ + @Generated + public static BlobReference fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String blobUri = null; + String storageAccountArmId = null; + SasCredential credential = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("blobUri".equals(fieldName)) { + blobUri = reader.getString(); + } else if ("storageAccountArmId".equals(fieldName)) { + storageAccountArmId = reader.getString(); + } else if ("credential".equals(fieldName)) { + credential = SasCredential.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return new BlobReference(blobUri, storageAccountArmId, credential); + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Connection.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Connection.java new file mode 100644 index 000000000000..282b0c259fbe --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Connection.java @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.Map; + +/** + * Response from the list and get connections operations. + */ +@Immutable +public final class Connection implements JsonSerializable { + + /* + * The friendly name of the connection, provided by the user. + */ + @Generated + private String name; + + /* + * A unique identifier for the connection, generated by the service + */ + @Generated + private String id; + + /* + * Category of the connection + */ + @Generated + private ConnectionType type; + + /* + * The connection URL to be used for this service + */ + @Generated + private String target; + + /* + * Whether the connection is tagged as the default connection of its type + */ + @Generated + private boolean isDefault; + + /* + * The credentials used by the connection + */ + @Generated + private BaseCredentials credentials; + + /* + * Metadata of the connection + */ + @Generated + private Map metadata; + + /** + * Creates an instance of Connection class. + */ + @Generated + private Connection() { + } + + /** + * Get the name property: The friendly name of the connection, provided by the user. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the id property: A unique identifier for the connection, generated by the service. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the type property: Category of the connection. + * + * @return the type value. + */ + @Generated + public ConnectionType getType() { + return this.type; + } + + /** + * Get the target property: The connection URL to be used for this service. + * + * @return the target value. + */ + @Generated + public String getTarget() { + return this.target; + } + + /** + * Get the isDefault property: Whether the connection is tagged as the default connection of its type. + * + * @return the isDefault value. + */ + @Generated + public boolean isDefault() { + return this.isDefault; + } + + /** + * Get the credentials property: The credentials used by the connection. + * + * @return the credentials value. + */ + @Generated + public BaseCredentials getCredentials() { + return this.credentials; + } + + /** + * Get the metadata property: Metadata of the connection. + * + * @return the metadata value. + */ + @Generated + public Map getMetadata() { + return this.metadata; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Connection from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Connection if the JsonReader was pointing to an instance of it, or null if it was pointing + * to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the Connection. + */ + @Generated + public static Connection fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Connection deserializedConnection = new Connection(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + deserializedConnection.name = reader.getString(); + } else if ("id".equals(fieldName)) { + deserializedConnection.id = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedConnection.type = ConnectionType.fromString(reader.getString()); + } else if ("target".equals(fieldName)) { + deserializedConnection.target = reader.getString(); + } else if ("isDefault".equals(fieldName)) { + deserializedConnection.isDefault = reader.getBoolean(); + } else if ("credentials".equals(fieldName)) { + deserializedConnection.credentials = BaseCredentials.fromJson(reader); + } else if ("metadata".equals(fieldName)) { + Map metadata = reader.readMap(reader1 -> reader1.getString()); + deserializedConnection.metadata = metadata; + } else { + reader.skipChildren(); + } + } + return deserializedConnection; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ConnectionType.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ConnectionType.java new file mode 100644 index 000000000000..a843cafb151b --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ConnectionType.java @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The Type (or category) of the connection. + */ +public final class ConnectionType extends ExpandableStringEnum { + + /** + * Azure OpenAI Service. + */ + @Generated + public static final ConnectionType AZURE_OPEN_AI = fromString("AzureOpenAI"); + + /** + * Azure Blob Storage, with specified container. + */ + @Generated + public static final ConnectionType AZURE_BLOB_STORAGE = fromString("AzureBlob"); + + /** + * Azure Blob Storage, with container not specified (used by Agents). + */ + @Generated + public static final ConnectionType AZURE_STORAGE_ACCOUNT = fromString("AzureStorageAccount"); + + /** + * CosmosDB. + */ + @Generated + public static final ConnectionType COSMOS_DB = fromString("CosmosDB"); + + /** + * Generic connection that uses API Key authentication. + */ + @Generated + public static final ConnectionType APIKEY = fromString("ApiKey"); + + /** + * Application Configuration. + */ + @Generated + public static final ConnectionType APPLICATION_CONFIGURATION = fromString("AppConfig"); + + /** + * Application Insights. + */ + @Generated + public static final ConnectionType APPLICATION_INSIGHTS = fromString("AppInsights"); + + /** + * Custom Keys. + */ + @Generated + public static final ConnectionType CUSTOM = fromString("CustomKeys"); + + /** + * Creates a new instance of ConnectionType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public ConnectionType() { + } + + /** + * Creates or finds a ConnectionType from its string representation. + * + * @param name a name to look for. + * @return the corresponding ConnectionType. + */ + @Generated + public static ConnectionType fromString(String name) { + return fromString(name, ConnectionType.class); + } + + /** + * Gets known ConnectionType values. + * + * @return known ConnectionType values. + */ + @Generated + public static Collection values() { + return values(ConnectionType.class); + } + + /** + * Azure AI Search. + */ + @Generated + public static final ConnectionType AZURE_AI_SEARCH = fromString("CognitiveSearch"); +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/CosmosDBIndex.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/CosmosDBIndex.java new file mode 100644 index 000000000000..2c44376956ab --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/CosmosDBIndex.java @@ -0,0 +1,362 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * CosmosDB Vector Store Index Definition. + */ +@Fluent +public final class CosmosDBIndex extends Index { + + /* + * Type of index + */ + @Generated + private IndexType type = IndexType.COSMOS_DB; + + /* + * Name of connection to CosmosDB + */ + @Generated + private String connectionName; + + /* + * Name of the CosmosDB Database + */ + @Generated + private String databaseName; + + /* + * Name of CosmosDB Container + */ + @Generated + private String containerName; + + /* + * Embedding model configuration + */ + @Generated + private EmbeddingConfiguration embeddingConfiguration; + + /* + * Field mapping configuration + */ + @Generated + private FieldMapping fieldMapping; + + /** + * Stores updated model property, the value is property name, not serialized name. + */ + @Generated + private final Set updatedProperties = new HashSet<>(); + + /** + * Creates an instance of CosmosDBIndex class. + */ + @Generated + public CosmosDBIndex() { + } + + /** + * Get the type property: Type of index. + * + * @return the type value. + */ + @Generated + @Override + public IndexType getType() { + return this.type; + } + + /** + * Get the connectionName property: Name of connection to CosmosDB. + * + * @return the connectionName value. + */ + @Generated + public String getConnectionName() { + return this.connectionName; + } + + /** + * Set the connectionName property: Name of connection to CosmosDB. + *

Required when create the resource.

+ * + * @param connectionName the connectionName value to set. + * @return the CosmosDBIndex object itself. + */ + @Generated + public CosmosDBIndex setConnectionName(String connectionName) { + this.connectionName = connectionName; + this.updatedProperties.add("connectionName"); + return this; + } + + /** + * Get the databaseName property: Name of the CosmosDB Database. + * + * @return the databaseName value. + */ + @Generated + public String getDatabaseName() { + return this.databaseName; + } + + /** + * Set the databaseName property: Name of the CosmosDB Database. + *

Required when create the resource.

+ * + * @param databaseName the databaseName value to set. + * @return the CosmosDBIndex object itself. + */ + @Generated + public CosmosDBIndex setDatabaseName(String databaseName) { + this.databaseName = databaseName; + this.updatedProperties.add("databaseName"); + return this; + } + + /** + * Get the containerName property: Name of CosmosDB Container. + * + * @return the containerName value. + */ + @Generated + public String getContainerName() { + return this.containerName; + } + + /** + * Set the containerName property: Name of CosmosDB Container. + *

Required when create the resource.

+ * + * @param containerName the containerName value to set. + * @return the CosmosDBIndex object itself. + */ + @Generated + public CosmosDBIndex setContainerName(String containerName) { + this.containerName = containerName; + this.updatedProperties.add("containerName"); + return this; + } + + /** + * Get the embeddingConfiguration property: Embedding model configuration. + * + * @return the embeddingConfiguration value. + */ + @Generated + public EmbeddingConfiguration getEmbeddingConfiguration() { + return this.embeddingConfiguration; + } + + /** + * Set the embeddingConfiguration property: Embedding model configuration. + *

Required when create the resource.

+ * + * @param embeddingConfiguration the embeddingConfiguration value to set. + * @return the CosmosDBIndex object itself. + */ + @Generated + public CosmosDBIndex setEmbeddingConfiguration(EmbeddingConfiguration embeddingConfiguration) { + this.embeddingConfiguration = embeddingConfiguration; + this.updatedProperties.add("embeddingConfiguration"); + return this; + } + + /** + * Get the fieldMapping property: Field mapping configuration. + * + * @return the fieldMapping value. + */ + @Generated + public FieldMapping getFieldMapping() { + return this.fieldMapping; + } + + /** + * Set the fieldMapping property: Field mapping configuration. + *

Required when create the resource.

+ * + * @param fieldMapping the fieldMapping value to set. + * @return the CosmosDBIndex object itself. + */ + @Generated + public CosmosDBIndex setFieldMapping(FieldMapping fieldMapping) { + this.fieldMapping = fieldMapping; + this.updatedProperties.add("fieldMapping"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public CosmosDBIndex setDescription(String description) { + super.setDescription(description); + this.updatedProperties.add("description"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public CosmosDBIndex setTags(Map tags) { + super.setTags(tags); + this.updatedProperties.add("tags"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + if (JsonMergePatchHelper.getIndexAccessor().isJsonMergePatch(this)) { + return toJsonMergePatch(jsonWriter); + } else { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("description", getDescription()); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeStringField("connectionName", this.connectionName); + jsonWriter.writeStringField("databaseName", this.databaseName); + jsonWriter.writeStringField("containerName", this.containerName); + jsonWriter.writeJsonField("embeddingConfiguration", this.embeddingConfiguration); + jsonWriter.writeJsonField("fieldMapping", this.fieldMapping); + return jsonWriter.writeEndObject(); + } + } + + @Generated + private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + if (updatedProperties.contains("description")) { + if (getDescription() == null) { + jsonWriter.writeNullField("description"); + } else { + jsonWriter.writeStringField("description", getDescription()); + } + } + if (updatedProperties.contains("tags")) { + if (getTags() == null) { + jsonWriter.writeNullField("tags"); + } else { + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> { + if (element != null) { + writer.writeString(element); + } else { + writer.writeNull(); + } + }); + } + } + jsonWriter.writeStringField("type", this.type.toString()); + if (updatedProperties.contains("connectionName")) { + if (this.connectionName == null) { + jsonWriter.writeNullField("connectionName"); + } else { + jsonWriter.writeStringField("connectionName", this.connectionName); + } + } + if (updatedProperties.contains("databaseName")) { + if (this.databaseName == null) { + jsonWriter.writeNullField("databaseName"); + } else { + jsonWriter.writeStringField("databaseName", this.databaseName); + } + } + if (updatedProperties.contains("containerName")) { + if (this.containerName == null) { + jsonWriter.writeNullField("containerName"); + } else { + jsonWriter.writeStringField("containerName", this.containerName); + } + } + if (updatedProperties.contains("embeddingConfiguration")) { + if (this.embeddingConfiguration == null) { + jsonWriter.writeNullField("embeddingConfiguration"); + } else { + JsonMergePatchHelper.getEmbeddingConfigurationAccessor() + .prepareModelForJsonMergePatch(this.embeddingConfiguration, true); + jsonWriter.writeJsonField("embeddingConfiguration", this.embeddingConfiguration); + JsonMergePatchHelper.getEmbeddingConfigurationAccessor() + .prepareModelForJsonMergePatch(this.embeddingConfiguration, false); + } + } + if (updatedProperties.contains("fieldMapping")) { + if (this.fieldMapping == null) { + jsonWriter.writeNullField("fieldMapping"); + } else { + JsonMergePatchHelper.getFieldMappingAccessor().prepareModelForJsonMergePatch(this.fieldMapping, true); + jsonWriter.writeJsonField("fieldMapping", this.fieldMapping); + JsonMergePatchHelper.getFieldMappingAccessor().prepareModelForJsonMergePatch(this.fieldMapping, false); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CosmosDBIndex from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CosmosDBIndex if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the CosmosDBIndex. + */ + @Generated + public static CosmosDBIndex fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CosmosDBIndex deserializedCosmosDBIndex = new CosmosDBIndex(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor().setName(deserializedCosmosDBIndex, reader.getString()); + } else if ("version".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor().setVersion(deserializedCosmosDBIndex, reader.getString()); + } else if ("id".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor().setId(deserializedCosmosDBIndex, reader.getString()); + } else if ("description".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor() + .setDescription(deserializedCosmosDBIndex, reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + JsonMergePatchHelper.getIndexAccessor().setTags(deserializedCosmosDBIndex, tags); + } else if ("type".equals(fieldName)) { + deserializedCosmosDBIndex.type = IndexType.fromString(reader.getString()); + } else if ("connectionName".equals(fieldName)) { + deserializedCosmosDBIndex.connectionName = reader.getString(); + } else if ("databaseName".equals(fieldName)) { + deserializedCosmosDBIndex.databaseName = reader.getString(); + } else if ("containerName".equals(fieldName)) { + deserializedCosmosDBIndex.containerName = reader.getString(); + } else if ("embeddingConfiguration".equals(fieldName)) { + deserializedCosmosDBIndex.embeddingConfiguration = EmbeddingConfiguration.fromJson(reader); + } else if ("fieldMapping".equals(fieldName)) { + deserializedCosmosDBIndex.fieldMapping = FieldMapping.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedCosmosDBIndex; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/CredentialType.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/CredentialType.java new file mode 100644 index 000000000000..47752861bcd9 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/CredentialType.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The credential type used by the connection. + */ +public final class CredentialType extends ExpandableStringEnum { + + /** + * API Key credential. + */ + @Generated + public static final CredentialType API_KEY = fromString("ApiKey"); + + /** + * Entra ID credential (formerly known as AAD). + */ + @Generated + public static final CredentialType ENTRA_ID = fromString("AAD"); + + /** + * Shared Access Signature (SAS) credential. + */ + @Generated + public static final CredentialType SAS = fromString("SAS"); + + /** + * Custom credential. + */ + @Generated + public static final CredentialType CUSTOM = fromString("CustomKeys"); + + /** + * No credential. + */ + @Generated + public static final CredentialType NONE = fromString("None"); + + /** + * Creates a new instance of CredentialType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public CredentialType() { + } + + /** + * Creates or finds a CredentialType from its string representation. + * + * @param name a name to look for. + * @return the corresponding CredentialType. + */ + @Generated + public static CredentialType fromString(String name) { + return fromString(name, CredentialType.class); + } + + /** + * Gets known CredentialType values. + * + * @return known CredentialType values. + */ + @Generated + public static Collection values() { + return values(CredentialType.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/CustomCredential.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/CustomCredential.java new file mode 100644 index 000000000000..01dfba5bcaed --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/CustomCredential.java @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.Map; + +/** + * Custom credential definition. + */ +@Immutable +public final class CustomCredential extends BaseCredentials { + + /* + * The type of credential used by the connection + */ + @Generated + private CredentialType type = CredentialType.CUSTOM; + + /* + * The credential type + */ + @Generated + private Map keys; + + /** + * Creates an instance of CustomCredential class. + */ + @Generated + private CustomCredential() { + } + + /** + * Get the type property: The type of credential used by the connection. + * + * @return the type value. + */ + @Generated + @Override + public CredentialType getType() { + return this.type; + } + + /** + * Get the keys property: The credential type. + * + * @return the keys value. + */ + @Generated + public Map getKeys() { + return this.keys; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CustomCredential from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CustomCredential if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the CustomCredential. + */ + @Generated + public static CustomCredential fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CustomCredential deserializedCustomCredential = new CustomCredential(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("keys".equals(fieldName)) { + Map keys = reader.readMap(reader1 -> reader1.getString()); + deserializedCustomCredential.keys = keys; + } else if ("type".equals(fieldName)) { + deserializedCustomCredential.type = CredentialType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedCustomCredential; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/DatasetType.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/DatasetType.java new file mode 100644 index 000000000000..7df144c95005 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/DatasetType.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Enum to determine the type of data. + */ +public final class DatasetType extends ExpandableStringEnum { + + /** + * URI file. + */ + @Generated + public static final DatasetType URI_FILE = fromString("uri_file"); + + /** + * URI folder. + */ + @Generated + public static final DatasetType URI_FOLDER = fromString("uri_folder"); + + /** + * Creates a new instance of DatasetType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public DatasetType() { + } + + /** + * Creates or finds a DatasetType from its string representation. + * + * @param name a name to look for. + * @return the corresponding DatasetType. + */ + @Generated + public static DatasetType fromString(String name) { + return fromString(name, DatasetType.class); + } + + /** + * Gets known DatasetType values. + * + * @return known DatasetType values. + */ + @Generated + public static Collection values() { + return values(DatasetType.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/DatasetVersion.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/DatasetVersion.java new file mode 100644 index 000000000000..423d3f8a68eb --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/DatasetVersion.java @@ -0,0 +1,434 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * DatasetVersion Definition. + */ +@Fluent +public class DatasetVersion implements JsonSerializable { + + /* + * Dataset type + */ + @Generated + private DatasetType type = DatasetType.fromString("DatasetVersion"); + + /* + * URI of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330 + */ + @Generated + private String dataUri; + + /* + * Indicates if the dataset holds a reference to the storage, or the dataset manages storage itself. If true, the + * underlying data will not be deleted when the dataset version is deleted + */ + @Generated + private Boolean isReference; + + /* + * Asset ID, a unique identifier for the asset + */ + @Generated + private String id; + + /* + * The name of the resource + */ + @Generated + private String name; + + /* + * The version of the resource + */ + @Generated + private String version; + + /* + * The asset description text. + */ + @Generated + private String description; + + /* + * Tag dictionary. Tags can be added, removed, and updated. + */ + @Generated + private Map tags; + + /** + * Stores updated model property, the value is property name, not serialized name. + */ + @Generated + private final Set updatedProperties = new HashSet<>(); + + @Generated + private boolean jsonMergePatch; + + @Generated + private void serializeAsJsonMergePatch(boolean jsonMergePatch) { + this.jsonMergePatch = jsonMergePatch; + } + + static { + JsonMergePatchHelper.setDatasetVersionAccessor(new JsonMergePatchHelper.DatasetVersionAccessor() { + + @Override + public DatasetVersion prepareModelForJsonMergePatch(DatasetVersion model, boolean jsonMergePatchEnabled) { + model.serializeAsJsonMergePatch(jsonMergePatchEnabled); + return model; + } + + @Override + public boolean isJsonMergePatch(DatasetVersion model) { + return model.jsonMergePatch; + } + + @Override + public void setDataUri(DatasetVersion model, String dataUri) { + model.dataUri = dataUri; + } + + @Override + public void setIsReference(DatasetVersion model, Boolean isReference) { + model.isReference = isReference; + } + + @Override + public void setConnectionName(DatasetVersion model, String connectionName) { + model.connectionName = connectionName; + } + + @Override + public void setId(DatasetVersion model, String id) { + model.id = id; + } + + @Override + public void setName(DatasetVersion model, String name) { + model.name = name; + } + + @Override + public void setVersion(DatasetVersion model, String version) { + model.version = version; + } + + @Override + public void setDescription(DatasetVersion model, String description) { + model.description = description; + } + + @Override + public void setTags(DatasetVersion model, Map tags) { + model.tags = tags; + } + }); + } + + /** + * Creates an instance of DatasetVersion class. + */ + @Generated + public DatasetVersion() { + } + + /** + * Get the type property: Dataset type. + * + * @return the type value. + */ + @Generated + public DatasetType getType() { + return this.type; + } + + /** + * Get the dataUri property: URI of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + * + * @return the dataUri value. + */ + @Generated + public String getDataUri() { + return this.dataUri; + } + + /** + * Set the dataUri property: URI of the data. Example: https://go.microsoft.com/fwlink/?linkid=2202330. + *

Required when create the resource.

+ * + * @param dataUri the dataUri value to set. + * @return the DatasetVersion object itself. + */ + @Generated + public DatasetVersion setDataUri(String dataUri) { + this.dataUri = dataUri; + this.updatedProperties.add("dataUri"); + return this; + } + + /** + * Get the isReference property: Indicates if the dataset holds a reference to the storage, or the dataset manages + * storage itself. If true, the underlying data will not be deleted when the dataset version is deleted. + * + * @return the isReference value. + */ + @Generated + public Boolean isReference() { + return this.isReference; + } + + /** + * Get the id property: Asset ID, a unique identifier for the asset. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the version property: The version of the resource. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the description property: The asset description text. + * + * @return the description value. + */ + @Generated + public String getDescription() { + return this.description; + } + + /** + * Set the description property: The asset description text. + * + * @param description the description value to set. + * @return the DatasetVersion object itself. + */ + @Generated + public DatasetVersion setDescription(String description) { + this.description = description; + this.updatedProperties.add("description"); + return this; + } + + /** + * Get the tags property: Tag dictionary. Tags can be added, removed, and updated. + * + * @return the tags value. + */ + @Generated + public Map getTags() { + return this.tags; + } + + /** + * Set the tags property: Tag dictionary. Tags can be added, removed, and updated. + * + * @param tags the tags value to set. + * @return the DatasetVersion object itself. + */ + @Generated + public DatasetVersion setTags(Map tags) { + this.tags = tags; + this.updatedProperties.add("tags"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + if (jsonMergePatch) { + return toJsonMergePatch(jsonWriter); + } else { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeStringField("dataUri", this.dataUri); + jsonWriter.writeStringField("connectionName", this.connectionName); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + } + + @Generated + private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type.toString()); + if (updatedProperties.contains("dataUri")) { + if (this.dataUri == null) { + jsonWriter.writeNullField("dataUri"); + } else { + jsonWriter.writeStringField("dataUri", this.dataUri); + } + } + if (updatedProperties.contains("connectionName")) { + if (this.connectionName == null) { + jsonWriter.writeNullField("connectionName"); + } else { + jsonWriter.writeStringField("connectionName", this.connectionName); + } + } + if (updatedProperties.contains("description")) { + if (this.description == null) { + jsonWriter.writeNullField("description"); + } else { + jsonWriter.writeStringField("description", this.description); + } + } + if (updatedProperties.contains("tags")) { + if (this.tags == null) { + jsonWriter.writeNullField("tags"); + } else { + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> { + if (element != null) { + writer.writeString(element); + } else { + writer.writeNull(); + } + }); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DatasetVersion from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DatasetVersion if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the DatasetVersion. + */ + @Generated + public static DatasetVersion fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("uri_file".equals(discriminatorValue)) { + return FileDatasetVersion.fromJson(readerToUse.reset()); + } else if ("uri_folder".equals(discriminatorValue)) { + return FolderDatasetVersion.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static DatasetVersion fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DatasetVersion deserializedDatasetVersion = new DatasetVersion(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + deserializedDatasetVersion.name = reader.getString(); + } else if ("version".equals(fieldName)) { + deserializedDatasetVersion.version = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedDatasetVersion.type = DatasetType.fromString(reader.getString()); + } else if ("dataUri".equals(fieldName)) { + deserializedDatasetVersion.dataUri = reader.getString(); + } else if ("isReference".equals(fieldName)) { + deserializedDatasetVersion.isReference = reader.getNullable(JsonReader::getBoolean); + } else if ("connectionName".equals(fieldName)) { + deserializedDatasetVersion.connectionName = reader.getString(); + } else if ("id".equals(fieldName)) { + deserializedDatasetVersion.id = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedDatasetVersion.description = reader.getString(); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedDatasetVersion.tags = tags; + } else { + reader.skipChildren(); + } + } + return deserializedDatasetVersion; + }); + } + + /* + * The Azure Storage Account connection name. Required if startPendingUploadVersion was not called before creating + * the Dataset + */ + @Generated + private String connectionName; + + /** + * Get the connectionName property: The Azure Storage Account connection name. Required if startPendingUploadVersion + * was not called before creating the Dataset. + * + * @return the connectionName value. + */ + @Generated + public String getConnectionName() { + return this.connectionName; + } + + /** + * Set the connectionName property: The Azure Storage Account connection name. Required if startPendingUploadVersion + * was not called before creating the Dataset. + * + * @param connectionName the connectionName value to set. + * @return the DatasetVersion object itself. + */ + @Generated + public DatasetVersion setConnectionName(String connectionName) { + this.connectionName = connectionName; + this.updatedProperties.add("connectionName"); + return this; + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Deployment.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Deployment.java new file mode 100644 index 000000000000..657f94ce83bb --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Deployment.java @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Model Deployment Definition. + */ +@Immutable +public class Deployment implements JsonSerializable { + + /* + * The type of the deployment + */ + @Generated + private DeploymentType type = DeploymentType.fromString("Deployment"); + + /* + * Name of the deployment + */ + @Generated + private String name; + + /** + * Creates an instance of Deployment class. + */ + @Generated + protected Deployment() { + } + + /** + * Get the type property: The type of the deployment. + * + * @return the type value. + */ + @Generated + public DeploymentType getType() { + return this.type; + } + + /** + * Get the name property: Name of the deployment. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Set the name property: Name of the deployment. + * + * @param name the name value to set. + * @return the Deployment object itself. + */ + @Generated + Deployment setName(String name) { + this.name = name; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Deployment from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Deployment if the JsonReader was pointing to an instance of it, or null if it was pointing + * to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the Deployment. + */ + @Generated + public static Deployment fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("ModelDeployment".equals(discriminatorValue)) { + return ModelDeployment.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static Deployment fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Deployment deserializedDeployment = new Deployment(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + deserializedDeployment.name = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedDeployment.type = DeploymentType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedDeployment; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/DeploymentType.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/DeploymentType.java new file mode 100644 index 000000000000..b3c3d57f6931 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/DeploymentType.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for DeploymentType. + */ +public final class DeploymentType extends ExpandableStringEnum { + + /** + * Model deployment. + */ + @Generated + public static final DeploymentType MODEL_DEPLOYMENT = fromString("ModelDeployment"); + + /** + * Creates a new instance of DeploymentType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public DeploymentType() { + } + + /** + * Creates or finds a DeploymentType from its string representation. + * + * @param name a name to look for. + * @return the corresponding DeploymentType. + */ + @Generated + public static DeploymentType fromString(String name) { + return fromString(name, DeploymentType.class); + } + + /** + * Gets known DeploymentType values. + * + * @return known DeploymentType values. + */ + @Generated + public static Collection values() { + return values(DeploymentType.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EmbeddingConfiguration.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EmbeddingConfiguration.java new file mode 100644 index 000000000000..e758ab409b41 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EmbeddingConfiguration.java @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +/** + * Embedding configuration class. + */ +@Fluent +public final class EmbeddingConfiguration implements JsonSerializable { + + /* + * Deployment name of embedding model. It can point to a model deployment either in the parent AIServices or a + * connection. + */ + @Generated + private String modelDeploymentName; + + /* + * Embedding field + */ + @Generated + private String embeddingField; + + /** + * Stores updated model property, the value is property name, not serialized name. + */ + @Generated + private final Set updatedProperties = new HashSet<>(); + + @Generated + private boolean jsonMergePatch; + + @Generated + private void serializeAsJsonMergePatch(boolean jsonMergePatch) { + this.jsonMergePatch = jsonMergePatch; + } + + static { + JsonMergePatchHelper + .setEmbeddingConfigurationAccessor(new JsonMergePatchHelper.EmbeddingConfigurationAccessor() { + + @Override + public EmbeddingConfiguration prepareModelForJsonMergePatch(EmbeddingConfiguration model, + boolean jsonMergePatchEnabled) { + model.serializeAsJsonMergePatch(jsonMergePatchEnabled); + return model; + } + + @Override + public boolean isJsonMergePatch(EmbeddingConfiguration model) { + return model.jsonMergePatch; + } + }); + } + + /** + * Creates an instance of EmbeddingConfiguration class. + */ + @Generated + public EmbeddingConfiguration() { + } + + /** + * Get the modelDeploymentName property: Deployment name of embedding model. It can point to a model deployment + * either in the parent AIServices or a connection. + * + * @return the modelDeploymentName value. + */ + @Generated + public String getModelDeploymentName() { + return this.modelDeploymentName; + } + + /** + * Set the modelDeploymentName property: Deployment name of embedding model. It can point to a model deployment + * either in the parent AIServices or a connection. + *

Required when create the resource.

+ * + * @param modelDeploymentName the modelDeploymentName value to set. + * @return the EmbeddingConfiguration object itself. + */ + @Generated + public EmbeddingConfiguration setModelDeploymentName(String modelDeploymentName) { + this.modelDeploymentName = modelDeploymentName; + this.updatedProperties.add("modelDeploymentName"); + return this; + } + + /** + * Get the embeddingField property: Embedding field. + * + * @return the embeddingField value. + */ + @Generated + public String getEmbeddingField() { + return this.embeddingField; + } + + /** + * Set the embeddingField property: Embedding field. + *

Required when create the resource.

+ * + * @param embeddingField the embeddingField value to set. + * @return the EmbeddingConfiguration object itself. + */ + @Generated + public EmbeddingConfiguration setEmbeddingField(String embeddingField) { + this.embeddingField = embeddingField; + this.updatedProperties.add("embeddingField"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + if (jsonMergePatch) { + return toJsonMergePatch(jsonWriter); + } else { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("modelDeploymentName", this.modelDeploymentName); + jsonWriter.writeStringField("embeddingField", this.embeddingField); + return jsonWriter.writeEndObject(); + } + } + + @Generated + private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + if (updatedProperties.contains("modelDeploymentName")) { + if (this.modelDeploymentName == null) { + jsonWriter.writeNullField("modelDeploymentName"); + } else { + jsonWriter.writeStringField("modelDeploymentName", this.modelDeploymentName); + } + } + if (updatedProperties.contains("embeddingField")) { + if (this.embeddingField == null) { + jsonWriter.writeNullField("embeddingField"); + } else { + jsonWriter.writeStringField("embeddingField", this.embeddingField); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EmbeddingConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EmbeddingConfiguration if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IOException If an error occurs while reading the EmbeddingConfiguration. + */ + @Generated + public static EmbeddingConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + EmbeddingConfiguration deserializedEmbeddingConfiguration = new EmbeddingConfiguration(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("modelDeploymentName".equals(fieldName)) { + deserializedEmbeddingConfiguration.modelDeploymentName = reader.getString(); + } else if ("embeddingField".equals(fieldName)) { + deserializedEmbeddingConfiguration.embeddingField = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedEmbeddingConfiguration; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EntraIDCredentials.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EntraIDCredentials.java new file mode 100644 index 000000000000..af7b607d26bc --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EntraIDCredentials.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Entra ID credential definition. + */ +@Immutable +public final class EntraIDCredentials extends BaseCredentials { + + /* + * The type of credential used by the connection + */ + @Generated + private CredentialType type = CredentialType.ENTRA_ID; + + /** + * Creates an instance of EntraIDCredentials class. + */ + @Generated + private EntraIDCredentials() { + } + + /** + * Get the type property: The type of credential used by the connection. + * + * @return the type value. + */ + @Generated + @Override + public CredentialType getType() { + return this.type; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EntraIDCredentials from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EntraIDCredentials if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the EntraIDCredentials. + */ + @Generated + public static EntraIDCredentials fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + EntraIDCredentials deserializedEntraIDCredentials = new EntraIDCredentials(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedEntraIDCredentials.type = CredentialType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedEntraIDCredentials; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Evaluation.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Evaluation.java new file mode 100644 index 000000000000..1032f4c2d403 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Evaluation.java @@ -0,0 +1,285 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.Map; + +/** + * Evaluation Definition. + */ +@Fluent +public final class Evaluation implements JsonSerializable { + + /* + * Identifier of the evaluation. + */ + @Generated + private String name; + + /* + * Data for evaluation. + */ + @Generated + private final InputData data; + + /* + * Display Name for evaluation. It helps to find the evaluation easily in AI Foundry. It does not need to be unique. + */ + @Generated + private String displayName; + + /* + * Description of the evaluation. It can be used to store additional information about the evaluation and is + * mutable. + */ + @Generated + private String description; + + /* + * Status of the evaluation. It is set by service and is read-only. + */ + @Generated + private String status; + + /* + * Evaluation's tags. Unlike properties, tags are fully mutable. + */ + @Generated + private Map tags; + + /* + * Evaluation's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + */ + @Generated + private Map properties; + + /* + * Evaluators to be used for the evaluation. + */ + @Generated + private final Map evaluators; + + /** + * Creates an instance of Evaluation class. + * + * @param data the data value to set. + * @param evaluators the evaluators value to set. + */ + @Generated + public Evaluation(InputData data, Map evaluators) { + this.data = data; + this.evaluators = evaluators; + } + + /** + * Get the name property: Identifier of the evaluation. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the data property: Data for evaluation. + * + * @return the data value. + */ + @Generated + public InputData getData() { + return this.data; + } + + /** + * Get the displayName property: Display Name for evaluation. It helps to find the evaluation easily in AI Foundry. + * It does not need to be unique. + * + * @return the displayName value. + */ + @Generated + public String getDisplayName() { + return this.displayName; + } + + /** + * Set the displayName property: Display Name for evaluation. It helps to find the evaluation easily in AI Foundry. + * It does not need to be unique. + * + * @param displayName the displayName value to set. + * @return the Evaluation object itself. + */ + @Generated + public Evaluation setDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get the description property: Description of the evaluation. It can be used to store additional information about + * the evaluation and is mutable. + * + * @return the description value. + */ + @Generated + public String getDescription() { + return this.description; + } + + /** + * Set the description property: Description of the evaluation. It can be used to store additional information about + * the evaluation and is mutable. + * + * @param description the description value to set. + * @return the Evaluation object itself. + */ + @Generated + public Evaluation setDescription(String description) { + this.description = description; + return this; + } + + /** + * Get the status property: Status of the evaluation. It is set by service and is read-only. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the tags property: Evaluation's tags. Unlike properties, tags are fully mutable. + * + * @return the tags value. + */ + @Generated + public Map getTags() { + return this.tags; + } + + /** + * Set the tags property: Evaluation's tags. Unlike properties, tags are fully mutable. + * + * @param tags the tags value to set. + * @return the Evaluation object itself. + */ + @Generated + public Evaluation setTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the properties property: Evaluation's properties. Unlike tags, properties are add-only. Once added, a + * property cannot be removed. + * + * @return the properties value. + */ + @Generated + public Map getProperties() { + return this.properties; + } + + /** + * Set the properties property: Evaluation's properties. Unlike tags, properties are add-only. Once added, a + * property cannot be removed. + * + * @param properties the properties value to set. + * @return the Evaluation object itself. + */ + @Generated + public Evaluation setProperties(Map properties) { + this.properties = properties; + return this; + } + + /** + * Get the evaluators property: Evaluators to be used for the evaluation. + * + * @return the evaluators value. + */ + @Generated + public Map getEvaluators() { + return this.evaluators; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("data", this.data); + jsonWriter.writeMapField("evaluators", this.evaluators, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("displayName", this.displayName); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("properties", this.properties, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Evaluation from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Evaluation if the JsonReader was pointing to an instance of it, or null if it was pointing + * to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the Evaluation. + */ + @Generated + public static Evaluation fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + InputData data = null; + Map evaluators = null; + String displayName = null; + String description = null; + String status = null; + Map tags = null; + Map properties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + name = reader.getString(); + } else if ("data".equals(fieldName)) { + data = InputData.fromJson(reader); + } else if ("evaluators".equals(fieldName)) { + evaluators = reader.readMap(reader1 -> EvaluatorConfiguration.fromJson(reader1)); + } else if ("displayName".equals(fieldName)) { + displayName = reader.getString(); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("properties".equals(fieldName)) { + properties = reader.readMap(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + Evaluation deserializedEvaluation = new Evaluation(data, evaluators); + deserializedEvaluation.name = name; + deserializedEvaluation.displayName = displayName; + deserializedEvaluation.description = description; + deserializedEvaluation.status = status; + deserializedEvaluation.tags = tags; + deserializedEvaluation.properties = properties; + return deserializedEvaluation; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EvaluatorConfiguration.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EvaluatorConfiguration.java new file mode 100644 index 000000000000..ec1df7f936d7 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EvaluatorConfiguration.java @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.core.util.BinaryData; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.Map; + +/** + * Evaluator Configuration. + */ +@Fluent +public final class EvaluatorConfiguration implements JsonSerializable { + + /* + * Identifier of the evaluator. + */ + @Generated + private final String id; + + /* + * Initialization parameters of the evaluator. + */ + @Generated + private Map initParams; + + /* + * Data parameters of the evaluator. + */ + @Generated + private Map dataMapping; + + /** + * Creates an instance of EvaluatorConfiguration class. + * + * @param id the id value to set. + */ + @Generated + public EvaluatorConfiguration(String id) { + this.id = id; + } + + /** + * Get the id property: Identifier of the evaluator. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the initParams property: Initialization parameters of the evaluator. + * + * @return the initParams value. + */ + @Generated + public Map getInitParams() { + return this.initParams; + } + + /** + * Set the initParams property: Initialization parameters of the evaluator. + * + * @param initParams the initParams value to set. + * @return the EvaluatorConfiguration object itself. + */ + @Generated + public EvaluatorConfiguration setInitParams(Map initParams) { + this.initParams = initParams; + return this; + } + + /** + * Get the dataMapping property: Data parameters of the evaluator. + * + * @return the dataMapping value. + */ + @Generated + public Map getDataMapping() { + return this.dataMapping; + } + + /** + * Set the dataMapping property: Data parameters of the evaluator. + * + * @param dataMapping the dataMapping value to set. + * @return the EvaluatorConfiguration object itself. + */ + @Generated + public EvaluatorConfiguration setDataMapping(Map dataMapping) { + this.dataMapping = dataMapping; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeMapField("initParams", this.initParams, + (writer, element) -> writer.writeUntyped(element == null ? null : element.toObject(Object.class))); + jsonWriter.writeMapField("dataMapping", this.dataMapping, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of EvaluatorConfiguration from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EvaluatorConfiguration if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the EvaluatorConfiguration. + */ + @Generated + public static EvaluatorConfiguration fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + Map initParams = null; + Map dataMapping = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("initParams".equals(fieldName)) { + initParams = reader.readMap(reader1 -> reader1 + .getNullable(nonNullReader -> BinaryData.fromObject(nonNullReader.readUntyped()))); + } else if ("dataMapping".equals(fieldName)) { + dataMapping = reader.readMap(reader1 -> reader1.getString()); + } else { + reader.skipChildren(); + } + } + EvaluatorConfiguration deserializedEvaluatorConfiguration = new EvaluatorConfiguration(id); + deserializedEvaluatorConfiguration.initParams = initParams; + deserializedEvaluatorConfiguration.dataMapping = dataMapping; + return deserializedEvaluatorConfiguration; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EvaluatorId.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EvaluatorId.java new file mode 100644 index 000000000000..2a7562830ac0 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/EvaluatorId.java @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects.models; + +import com.azure.core.util.ExpandableStringEnum; + +/** + * EvaluatorId enumeration. + */ +public class EvaluatorId extends ExpandableStringEnum { + + /** + * Creates a new instance of EvaluatorId value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public EvaluatorId() { + } + + /** + * Creates or finds a EvaluatorId from its string representation. + * + * @param name a name to look for. + * @return the corresponding EvaluatorId. + */ + public static EvaluatorId fromString(String name) { + return fromString(name, EvaluatorId.class); + } + + /** + * EvaluatorId for relevance. + */ + public static final EvaluatorId RELEVANCE = fromString("azureai://built-in/evaluators/relevance"); + + /** + * EvaluatorId for hate_unfairness. + */ + public static final EvaluatorId HATE_UNFAIRNESS = fromString("azureai://built-in/evaluators/hate_unfairness"); + + /** + * EvaluatorId for violence. + */ + public static final EvaluatorId VIOLENCE = fromString("azureai://built-in/evaluators/violence"); + + /** + * EvaluatorId for groundedness. + */ + public static final EvaluatorId GROUNDEDNESS = fromString("azureai://built-in/evaluators/groundedness"); + + /** + * EvaluatorId for groundedness_pro. + */ + public static final EvaluatorId GROUNDEDNESS_PRO = fromString("azureai://built-in/evaluators/groundedness_pro"); + + /** + * EvaluatorId for blue_score. + */ + public static final EvaluatorId BLUE_SCORE = fromString("azureai://built-in/evaluators/blue_score"); + + /** + * EvaluatorId for code_vulnerability. + */ + public static final EvaluatorId CODE_VULNERABILITY = fromString("azureai://built-in/evaluators/code_vulnerability"); + + /** + * EvaluatorId for coherence. + */ + public static final EvaluatorId COHERENCE = fromString("azureai://built-in/evaluators/coherence"); + + /** + * EvaluatorId for content_safety. + */ + public static final EvaluatorId CONTENT_SAFETY = fromString("azureai://built-in/evaluators/content_safety"); + + /** + * EvaluatorId for f1_score. + */ + public static final EvaluatorId F1_SCORE = fromString("azureai://built-in/evaluators/f1_score"); + + /** + * EvaluatorId for fluency. + */ + public static final EvaluatorId FLUENCY = fromString("azureai://built-in/evaluators/fluency"); + + /** + * EvaluatorId for gleu_score. + */ + public static final EvaluatorId GLEU_SCORE = fromString("azureai://built-in/evaluators/gleu_score"); + + /** + * EvaluatorId for indirect_attack. + */ + public static final EvaluatorId INDIRECT_ATTACK = fromString("azureai://built-in/evaluators/indirect_attack"); + + /** + * EvaluatorId for intent_resolution. + */ + // public static final EvaluatorId INTENT_RESOLUTION = fromString("azureai://built-in/evaluators/intent_resolution"); + + /** + * EvaluatorId for meteor_score. + */ + public static final EvaluatorId METEOR_SCORE = fromString("azureai://built-in/evaluators/meteor_score"); + + /** + * EvaluatorId for protected_material. + */ + public static final EvaluatorId PROTECTED_MATERIAL = fromString("azureai://built-in/evaluators/protected_material"); + + /** + * EvaluatorId for retrieval. + */ + public static final EvaluatorId RETRIEVAL = fromString("azureai://built-in/evaluators/retrieval"); + + /** + * EvaluatorId for rouge_score. + */ + public static final EvaluatorId ROUGE_SCORE = fromString("azureai://built-in/evaluators/rouge_score"); + + /** + * EvaluatorId for self_harm. + */ + public static final EvaluatorId SELF_HARM = fromString("azureai://built-in/evaluators/self_harm"); + + /** + * EvaluatorId for sexual. + */ + public static final EvaluatorId SEXUAL = fromString("azureai://built-in/evaluators/sexual"); + + /** + * EvaluatorId for similarity_score. + */ + public static final EvaluatorId SIMILARITY_SCORE = fromString("azureai://built-in/evaluators/similarity_score"); + + /** + * EvaluatorId for task_adherence. + */ + // public static final EvaluatorId TASK_ADHERENCE = fromString("azureai://built-in/evaluators/task_adherence"); + + /** + * EvaluatorId for tool_call_accuracy. + */ + // public static final EvaluatorId TOOL_CALL_ACCURACY = fromString("azureai://built-in/evaluators/tool_call_accuracy"); + + /** + * EvaluatorId for ungrounded_attributes. + */ + public static final EvaluatorId UNGROUNDED_ATTRIBUTES + = fromString("azureai://built-in/evaluators/ungrounded_attributes"); + + /** + * EvaluatorId for response_completeness. + */ + public static final EvaluatorId RESPONSE_COMPLETENESS + = fromString("azureai://built-in/evaluators/response_completeness"); +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/FieldMapping.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/FieldMapping.java new file mode 100644 index 000000000000..5a25924f5f5d --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/FieldMapping.java @@ -0,0 +1,347 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Field mapping configuration class. + */ +@Fluent +public final class FieldMapping implements JsonSerializable { + + /* + * List of fields with text content + */ + @Generated + private List contentFields; + + /* + * Path of file to be used as a source of text content + */ + @Generated + private String filepathField; + + /* + * Field containing the title of the document + */ + @Generated + private String titleField; + + /* + * Field containing the url of the document + */ + @Generated + private String urlField; + + /* + * List of fields with vector content + */ + @Generated + private List vectorFields; + + /* + * List of fields with metadata content + */ + @Generated + private List metadataFields; + + /** + * Stores updated model property, the value is property name, not serialized name. + */ + @Generated + private final Set updatedProperties = new HashSet<>(); + + @Generated + private boolean jsonMergePatch; + + @Generated + private void serializeAsJsonMergePatch(boolean jsonMergePatch) { + this.jsonMergePatch = jsonMergePatch; + } + + static { + JsonMergePatchHelper.setFieldMappingAccessor(new JsonMergePatchHelper.FieldMappingAccessor() { + + @Override + public FieldMapping prepareModelForJsonMergePatch(FieldMapping model, boolean jsonMergePatchEnabled) { + model.serializeAsJsonMergePatch(jsonMergePatchEnabled); + return model; + } + + @Override + public boolean isJsonMergePatch(FieldMapping model) { + return model.jsonMergePatch; + } + }); + } + + /** + * Creates an instance of FieldMapping class. + */ + @Generated + public FieldMapping() { + } + + /** + * Get the contentFields property: List of fields with text content. + * + * @return the contentFields value. + */ + @Generated + public List getContentFields() { + return this.contentFields; + } + + /** + * Set the contentFields property: List of fields with text content. + *

Required when create the resource.

+ * + * @param contentFields the contentFields value to set. + * @return the FieldMapping object itself. + */ + @Generated + public FieldMapping setContentFields(List contentFields) { + this.contentFields = contentFields; + this.updatedProperties.add("contentFields"); + return this; + } + + /** + * Get the filepathField property: Path of file to be used as a source of text content. + * + * @return the filepathField value. + */ + @Generated + public String getFilepathField() { + return this.filepathField; + } + + /** + * Set the filepathField property: Path of file to be used as a source of text content. + * + * @param filepathField the filepathField value to set. + * @return the FieldMapping object itself. + */ + @Generated + public FieldMapping setFilepathField(String filepathField) { + this.filepathField = filepathField; + this.updatedProperties.add("filepathField"); + return this; + } + + /** + * Get the titleField property: Field containing the title of the document. + * + * @return the titleField value. + */ + @Generated + public String getTitleField() { + return this.titleField; + } + + /** + * Set the titleField property: Field containing the title of the document. + * + * @param titleField the titleField value to set. + * @return the FieldMapping object itself. + */ + @Generated + public FieldMapping setTitleField(String titleField) { + this.titleField = titleField; + this.updatedProperties.add("titleField"); + return this; + } + + /** + * Get the urlField property: Field containing the url of the document. + * + * @return the urlField value. + */ + @Generated + public String getUrlField() { + return this.urlField; + } + + /** + * Set the urlField property: Field containing the url of the document. + * + * @param urlField the urlField value to set. + * @return the FieldMapping object itself. + */ + @Generated + public FieldMapping setUrlField(String urlField) { + this.urlField = urlField; + this.updatedProperties.add("urlField"); + return this; + } + + /** + * Get the vectorFields property: List of fields with vector content. + * + * @return the vectorFields value. + */ + @Generated + public List getVectorFields() { + return this.vectorFields; + } + + /** + * Set the vectorFields property: List of fields with vector content. + * + * @param vectorFields the vectorFields value to set. + * @return the FieldMapping object itself. + */ + @Generated + public FieldMapping setVectorFields(List vectorFields) { + this.vectorFields = vectorFields; + this.updatedProperties.add("vectorFields"); + return this; + } + + /** + * Get the metadataFields property: List of fields with metadata content. + * + * @return the metadataFields value. + */ + @Generated + public List getMetadataFields() { + return this.metadataFields; + } + + /** + * Set the metadataFields property: List of fields with metadata content. + * + * @param metadataFields the metadataFields value to set. + * @return the FieldMapping object itself. + */ + @Generated + public FieldMapping setMetadataFields(List metadataFields) { + this.metadataFields = metadataFields; + this.updatedProperties.add("metadataFields"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + if (jsonMergePatch) { + return toJsonMergePatch(jsonWriter); + } else { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("contentFields", this.contentFields, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("filepathField", this.filepathField); + jsonWriter.writeStringField("titleField", this.titleField); + jsonWriter.writeStringField("urlField", this.urlField); + jsonWriter.writeArrayField("vectorFields", this.vectorFields, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeArrayField("metadataFields", this.metadataFields, + (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + } + + @Generated + private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + if (updatedProperties.contains("contentFields")) { + if (this.contentFields == null) { + jsonWriter.writeNullField("contentFields"); + } else { + jsonWriter.writeArrayField("contentFields", this.contentFields, + (writer, element) -> writer.writeString(element)); + } + } + if (updatedProperties.contains("filepathField")) { + if (this.filepathField == null) { + jsonWriter.writeNullField("filepathField"); + } else { + jsonWriter.writeStringField("filepathField", this.filepathField); + } + } + if (updatedProperties.contains("titleField")) { + if (this.titleField == null) { + jsonWriter.writeNullField("titleField"); + } else { + jsonWriter.writeStringField("titleField", this.titleField); + } + } + if (updatedProperties.contains("urlField")) { + if (this.urlField == null) { + jsonWriter.writeNullField("urlField"); + } else { + jsonWriter.writeStringField("urlField", this.urlField); + } + } + if (updatedProperties.contains("vectorFields")) { + if (this.vectorFields == null) { + jsonWriter.writeNullField("vectorFields"); + } else { + jsonWriter.writeArrayField("vectorFields", this.vectorFields, + (writer, element) -> writer.writeString(element)); + } + } + if (updatedProperties.contains("metadataFields")) { + if (this.metadataFields == null) { + jsonWriter.writeNullField("metadataFields"); + } else { + jsonWriter.writeArrayField("metadataFields", this.metadataFields, + (writer, element) -> writer.writeString(element)); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FieldMapping from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FieldMapping if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the FieldMapping. + */ + @Generated + public static FieldMapping fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FieldMapping deserializedFieldMapping = new FieldMapping(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("contentFields".equals(fieldName)) { + List contentFields = reader.readArray(reader1 -> reader1.getString()); + deserializedFieldMapping.contentFields = contentFields; + } else if ("filepathField".equals(fieldName)) { + deserializedFieldMapping.filepathField = reader.getString(); + } else if ("titleField".equals(fieldName)) { + deserializedFieldMapping.titleField = reader.getString(); + } else if ("urlField".equals(fieldName)) { + deserializedFieldMapping.urlField = reader.getString(); + } else if ("vectorFields".equals(fieldName)) { + List vectorFields = reader.readArray(reader1 -> reader1.getString()); + deserializedFieldMapping.vectorFields = vectorFields; + } else if ("metadataFields".equals(fieldName)) { + List metadataFields = reader.readArray(reader1 -> reader1.getString()); + deserializedFieldMapping.metadataFields = metadataFields; + } else { + reader.skipChildren(); + } + } + return deserializedFieldMapping; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/FileDatasetVersion.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/FileDatasetVersion.java new file mode 100644 index 000000000000..b22aa1ae6fa6 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/FileDatasetVersion.java @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * FileDatasetVersion Definition. + */ +@Fluent +public final class FileDatasetVersion extends DatasetVersion { + + /* + * Dataset type + */ + @Generated + private DatasetType type = DatasetType.URI_FILE; + + /** + * Stores updated model property, the value is property name, not serialized name. + */ + @Generated + private final Set updatedProperties = new HashSet<>(); + + /** + * Creates an instance of FileDatasetVersion class. + */ + @Generated + public FileDatasetVersion() { + } + + /** + * Get the type property: Dataset type. + * + * @return the type value. + */ + @Generated + @Override + public DatasetType getType() { + return this.type; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public FileDatasetVersion setDataUri(String dataUri) { + super.setDataUri(dataUri); + this.updatedProperties.add("dataUri"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public FileDatasetVersion setDescription(String description) { + super.setDescription(description); + this.updatedProperties.add("description"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public FileDatasetVersion setTags(Map tags) { + super.setTags(tags); + this.updatedProperties.add("tags"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + if (JsonMergePatchHelper.getDatasetVersionAccessor().isJsonMergePatch(this)) { + return toJsonMergePatch(jsonWriter); + } else { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("dataUri", getDataUri()); + jsonWriter.writeStringField("connectionName", getConnectionName()); + jsonWriter.writeStringField("description", getDescription()); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + } + + @Generated + private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + if (updatedProperties.contains("dataUri")) { + if (getDataUri() == null) { + jsonWriter.writeNullField("dataUri"); + } else { + jsonWriter.writeStringField("dataUri", getDataUri()); + } + } + if (updatedProperties.contains("connectionName")) { + if (getConnectionName() == null) { + jsonWriter.writeNullField("connectionName"); + } else { + jsonWriter.writeStringField("connectionName", getConnectionName()); + } + } + if (updatedProperties.contains("description")) { + if (getDescription() == null) { + jsonWriter.writeNullField("description"); + } else { + jsonWriter.writeStringField("description", getDescription()); + } + } + if (updatedProperties.contains("tags")) { + if (getTags() == null) { + jsonWriter.writeNullField("tags"); + } else { + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> { + if (element != null) { + writer.writeString(element); + } else { + writer.writeNull(); + } + }); + } + } + jsonWriter.writeStringField("type", this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FileDatasetVersion from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FileDatasetVersion if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the FileDatasetVersion. + */ + @Generated + public static FileDatasetVersion fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FileDatasetVersion deserializedFileDatasetVersion = new FileDatasetVersion(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setName(deserializedFileDatasetVersion, reader.getString()); + } else if ("version".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setVersion(deserializedFileDatasetVersion, reader.getString()); + } else if ("dataUri".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setDataUri(deserializedFileDatasetVersion, reader.getString()); + } else if ("isReference".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setIsReference(deserializedFileDatasetVersion, reader.getNullable(JsonReader::getBoolean)); + } else if ("connectionName".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setConnectionName(deserializedFileDatasetVersion, reader.getString()); + } else if ("id".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setId(deserializedFileDatasetVersion, reader.getString()); + } else if ("description".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setDescription(deserializedFileDatasetVersion, reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + JsonMergePatchHelper.getDatasetVersionAccessor().setTags(deserializedFileDatasetVersion, tags); + } else if ("type".equals(fieldName)) { + deserializedFileDatasetVersion.type = DatasetType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedFileDatasetVersion; + }); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public FileDatasetVersion setConnectionName(String connectionName) { + super.setConnectionName(connectionName); + this.updatedProperties.add("connectionName"); + return this; + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/FolderDatasetVersion.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/FolderDatasetVersion.java new file mode 100644 index 000000000000..d0222600b40a --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/FolderDatasetVersion.java @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * FileDatasetVersion Definition. + */ +@Fluent +public final class FolderDatasetVersion extends DatasetVersion { + + /* + * Dataset type + */ + @Generated + private DatasetType type = DatasetType.URI_FOLDER; + + /** + * Stores updated model property, the value is property name, not serialized name. + */ + @Generated + private final Set updatedProperties = new HashSet<>(); + + /** + * Creates an instance of FolderDatasetVersion class. + */ + @Generated + public FolderDatasetVersion() { + } + + /** + * Get the type property: Dataset type. + * + * @return the type value. + */ + @Generated + @Override + public DatasetType getType() { + return this.type; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public FolderDatasetVersion setDataUri(String dataUri) { + super.setDataUri(dataUri); + this.updatedProperties.add("dataUri"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public FolderDatasetVersion setDescription(String description) { + super.setDescription(description); + this.updatedProperties.add("description"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public FolderDatasetVersion setTags(Map tags) { + super.setTags(tags); + this.updatedProperties.add("tags"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + if (JsonMergePatchHelper.getDatasetVersionAccessor().isJsonMergePatch(this)) { + return toJsonMergePatch(jsonWriter); + } else { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("dataUri", getDataUri()); + jsonWriter.writeStringField("connectionName", getConnectionName()); + jsonWriter.writeStringField("description", getDescription()); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + } + + @Generated + private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + if (updatedProperties.contains("dataUri")) { + if (getDataUri() == null) { + jsonWriter.writeNullField("dataUri"); + } else { + jsonWriter.writeStringField("dataUri", getDataUri()); + } + } + if (updatedProperties.contains("connectionName")) { + if (getConnectionName() == null) { + jsonWriter.writeNullField("connectionName"); + } else { + jsonWriter.writeStringField("connectionName", getConnectionName()); + } + } + if (updatedProperties.contains("description")) { + if (getDescription() == null) { + jsonWriter.writeNullField("description"); + } else { + jsonWriter.writeStringField("description", getDescription()); + } + } + if (updatedProperties.contains("tags")) { + if (getTags() == null) { + jsonWriter.writeNullField("tags"); + } else { + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> { + if (element != null) { + writer.writeString(element); + } else { + writer.writeNull(); + } + }); + } + } + jsonWriter.writeStringField("type", this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of FolderDatasetVersion from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of FolderDatasetVersion if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the FolderDatasetVersion. + */ + @Generated + public static FolderDatasetVersion fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + FolderDatasetVersion deserializedFolderDatasetVersion = new FolderDatasetVersion(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setName(deserializedFolderDatasetVersion, reader.getString()); + } else if ("version".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setVersion(deserializedFolderDatasetVersion, reader.getString()); + } else if ("dataUri".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setDataUri(deserializedFolderDatasetVersion, reader.getString()); + } else if ("isReference".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setIsReference(deserializedFolderDatasetVersion, reader.getNullable(JsonReader::getBoolean)); + } else if ("connectionName".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setConnectionName(deserializedFolderDatasetVersion, reader.getString()); + } else if ("id".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setId(deserializedFolderDatasetVersion, reader.getString()); + } else if ("description".equals(fieldName)) { + JsonMergePatchHelper.getDatasetVersionAccessor() + .setDescription(deserializedFolderDatasetVersion, reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + JsonMergePatchHelper.getDatasetVersionAccessor().setTags(deserializedFolderDatasetVersion, tags); + } else if ("type".equals(fieldName)) { + deserializedFolderDatasetVersion.type = DatasetType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedFolderDatasetVersion; + }); + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public FolderDatasetVersion setConnectionName(String connectionName) { + super.setConnectionName(connectionName); + this.updatedProperties.add("connectionName"); + return this; + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Index.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Index.java new file mode 100644 index 000000000000..6f2a9058b28f --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Index.java @@ -0,0 +1,319 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Index resource Definition. + */ +@Fluent +public class Index implements JsonSerializable { + + /* + * Type of index + */ + @Generated + private IndexType type = IndexType.fromString("Index"); + + /* + * Asset ID, a unique identifier for the asset + */ + @Generated + private String id; + + /* + * The name of the resource + */ + @Generated + private String name; + + /* + * The version of the resource + */ + @Generated + private String version; + + /* + * The asset description text. + */ + @Generated + private String description; + + /* + * Tag dictionary. Tags can be added, removed, and updated. + */ + @Generated + private Map tags; + + /** + * Stores updated model property, the value is property name, not serialized name. + */ + @Generated + private final Set updatedProperties = new HashSet<>(); + + @Generated + private boolean jsonMergePatch; + + @Generated + private void serializeAsJsonMergePatch(boolean jsonMergePatch) { + this.jsonMergePatch = jsonMergePatch; + } + + static { + JsonMergePatchHelper.setIndexAccessor(new JsonMergePatchHelper.IndexAccessor() { + + @Override + public Index prepareModelForJsonMergePatch(Index model, boolean jsonMergePatchEnabled) { + model.serializeAsJsonMergePatch(jsonMergePatchEnabled); + return model; + } + + @Override + public boolean isJsonMergePatch(Index model) { + return model.jsonMergePatch; + } + + @Override + public void setId(Index model, String id) { + model.id = id; + } + + @Override + public void setName(Index model, String name) { + model.name = name; + } + + @Override + public void setVersion(Index model, String version) { + model.version = version; + } + + @Override + public void setDescription(Index model, String description) { + model.description = description; + } + + @Override + public void setTags(Index model, Map tags) { + model.tags = tags; + } + }); + } + + /** + * Creates an instance of Index class. + */ + @Generated + public Index() { + } + + /** + * Get the type property: Type of index. + * + * @return the type value. + */ + @Generated + public IndexType getType() { + return this.type; + } + + /** + * Get the id property: Asset ID, a unique identifier for the asset. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * Get the name property: The name of the resource. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the version property: The version of the resource. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the description property: The asset description text. + * + * @return the description value. + */ + @Generated + public String getDescription() { + return this.description; + } + + /** + * Set the description property: The asset description text. + * + * @param description the description value to set. + * @return the Index object itself. + */ + @Generated + public Index setDescription(String description) { + this.description = description; + this.updatedProperties.add("description"); + return this; + } + + /** + * Get the tags property: Tag dictionary. Tags can be added, removed, and updated. + * + * @return the tags value. + */ + @Generated + public Map getTags() { + return this.tags; + } + + /** + * Set the tags property: Tag dictionary. Tags can be added, removed, and updated. + * + * @param tags the tags value to set. + * @return the Index object itself. + */ + @Generated + public Index setTags(Map tags) { + this.tags = tags; + this.updatedProperties.add("tags"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + if (jsonMergePatch) { + return toJsonMergePatch(jsonWriter); + } else { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + } + + @Generated + private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type.toString()); + if (updatedProperties.contains("description")) { + if (this.description == null) { + jsonWriter.writeNullField("description"); + } else { + jsonWriter.writeStringField("description", this.description); + } + } + if (updatedProperties.contains("tags")) { + if (this.tags == null) { + jsonWriter.writeNullField("tags"); + } else { + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> { + if (element != null) { + writer.writeString(element); + } else { + writer.writeNull(); + } + }); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Index from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Index if the JsonReader was pointing to an instance of it, or null if it was pointing to + * JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the Index. + */ + @Generated + public static Index fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("AzureSearch".equals(discriminatorValue)) { + return AzureAISearchIndex.fromJson(readerToUse.reset()); + } else if ("ManagedAzureSearch".equals(discriminatorValue)) { + return ManagedAzureAISearchIndex.fromJson(readerToUse.reset()); + } else if ("CosmosDBNoSqlVectorStore".equals(discriminatorValue)) { + return CosmosDBIndex.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static Index fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Index deserializedIndex = new Index(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + deserializedIndex.name = reader.getString(); + } else if ("version".equals(fieldName)) { + deserializedIndex.version = reader.getString(); + } else if ("type".equals(fieldName)) { + deserializedIndex.type = IndexType.fromString(reader.getString()); + } else if ("id".equals(fieldName)) { + deserializedIndex.id = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedIndex.description = reader.getString(); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + deserializedIndex.tags = tags; + } else { + reader.skipChildren(); + } + } + return deserializedIndex; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/IndexType.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/IndexType.java new file mode 100644 index 000000000000..ebc391f475cb --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/IndexType.java @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Defines values for IndexType. + */ +public final class IndexType extends ExpandableStringEnum { + + /** + * Azure search. + */ + @Generated + public static final IndexType AZURE_SEARCH = fromString("AzureSearch"); + + /** + * CosmosDB. + */ + @Generated + public static final IndexType COSMOS_DB = fromString("CosmosDBNoSqlVectorStore"); + + /** + * Managed Azure Search. + */ + @Generated + public static final IndexType MANAGED_AZURE_SEARCH = fromString("ManagedAzureSearch"); + + /** + * Creates a new instance of IndexType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public IndexType() { + } + + /** + * Creates or finds a IndexType from its string representation. + * + * @param name a name to look for. + * @return the corresponding IndexType. + */ + @Generated + public static IndexType fromString(String name) { + return fromString(name, IndexType.class); + } + + /** + * Gets known IndexType values. + * + * @return known IndexType values. + */ + @Generated + public static Collection values() { + return values(IndexType.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/InputData.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/InputData.java new file mode 100644 index 000000000000..d6cf82e97c6b --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/InputData.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Abstract data class. + */ +@Immutable +public class InputData implements JsonSerializable { + + /* + * Type of the data + */ + @Generated + private String type = "InputData"; + + /** + * Creates an instance of InputData class. + */ + @Generated + public InputData() { + } + + /** + * Get the type property: Type of the data. + * + * @return the type value. + */ + @Generated + public String getType() { + return this.type; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of InputData from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of InputData if the JsonReader was pointing to an instance of it, or null if it was pointing + * to JSON null. + * @throws IOException If an error occurs while reading the InputData. + */ + @Generated + public static InputData fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("dataset".equals(discriminatorValue)) { + return InputDataset.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static InputData fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + InputData deserializedInputData = new InputData(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedInputData.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedInputData; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/InputDataset.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/InputDataset.java new file mode 100644 index 000000000000..289730e74ab2 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/InputDataset.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Dataset as source for evaluation. + */ +@Immutable +public final class InputDataset extends InputData { + + /* + * Type of the data + */ + @Generated + private String type = "dataset"; + + /* + * Evaluation input data + */ + @Generated + private final String id; + + /** + * Creates an instance of InputDataset class. + * + * @param id the id value to set. + */ + @Generated + public InputDataset(String id) { + this.id = id; + } + + /** + * Get the type property: Type of the data. + * + * @return the type value. + */ + @Generated + @Override + public String getType() { + return this.type; + } + + /** + * Get the id property: Evaluation input data. + * + * @return the id value. + */ + @Generated + public String getId() { + return this.id; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of InputDataset from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of InputDataset if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the InputDataset. + */ + @Generated + public static InputDataset fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + String type = "dataset"; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + InputDataset deserializedInputDataset = new InputDataset(id); + deserializedInputDataset.type = type; + return deserializedInputDataset; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ManagedAzureAISearchIndex.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ManagedAzureAISearchIndex.java new file mode 100644 index 000000000000..f73769a70c37 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ManagedAzureAISearchIndex.java @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.ai.projects.implementation.JsonMergePatchHelper; +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Managed Azure AI Search Index Definition. + */ +@Fluent +public final class ManagedAzureAISearchIndex extends Index { + + /* + * Type of index + */ + @Generated + private IndexType type = IndexType.MANAGED_AZURE_SEARCH; + + /* + * Vector store id of managed index + */ + @Generated + private String vectorStoreId; + + /** + * Stores updated model property, the value is property name, not serialized name. + */ + @Generated + private final Set updatedProperties = new HashSet<>(); + + /** + * Creates an instance of ManagedAzureAISearchIndex class. + */ + @Generated + public ManagedAzureAISearchIndex() { + } + + /** + * Get the type property: Type of index. + * + * @return the type value. + */ + @Generated + @Override + public IndexType getType() { + return this.type; + } + + /** + * Get the vectorStoreId property: Vector store id of managed index. + * + * @return the vectorStoreId value. + */ + @Generated + public String getVectorStoreId() { + return this.vectorStoreId; + } + + /** + * Set the vectorStoreId property: Vector store id of managed index. + *

Required when create the resource.

+ * + * @param vectorStoreId the vectorStoreId value to set. + * @return the ManagedAzureAISearchIndex object itself. + */ + @Generated + public ManagedAzureAISearchIndex setVectorStoreId(String vectorStoreId) { + this.vectorStoreId = vectorStoreId; + this.updatedProperties.add("vectorStoreId"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public ManagedAzureAISearchIndex setDescription(String description) { + super.setDescription(description); + this.updatedProperties.add("description"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public ManagedAzureAISearchIndex setTags(Map tags) { + super.setTags(tags); + this.updatedProperties.add("tags"); + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + if (JsonMergePatchHelper.getIndexAccessor().isJsonMergePatch(this)) { + return toJsonMergePatch(jsonWriter); + } else { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("description", getDescription()); + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeStringField("vectorStoreId", this.vectorStoreId); + return jsonWriter.writeEndObject(); + } + } + + @Generated + private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + if (updatedProperties.contains("description")) { + if (getDescription() == null) { + jsonWriter.writeNullField("description"); + } else { + jsonWriter.writeStringField("description", getDescription()); + } + } + if (updatedProperties.contains("tags")) { + if (getTags() == null) { + jsonWriter.writeNullField("tags"); + } else { + jsonWriter.writeMapField("tags", getTags(), (writer, element) -> { + if (element != null) { + writer.writeString(element); + } else { + writer.writeNull(); + } + }); + } + } + jsonWriter.writeStringField("type", this.type.toString()); + if (updatedProperties.contains("vectorStoreId")) { + if (this.vectorStoreId == null) { + jsonWriter.writeNullField("vectorStoreId"); + } else { + jsonWriter.writeStringField("vectorStoreId", this.vectorStoreId); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ManagedAzureAISearchIndex from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ManagedAzureAISearchIndex if the JsonReader was pointing to an instance of it, or null if + * it was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the ManagedAzureAISearchIndex. + */ + @Generated + public static ManagedAzureAISearchIndex fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ManagedAzureAISearchIndex deserializedManagedAzureAISearchIndex = new ManagedAzureAISearchIndex(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor() + .setName(deserializedManagedAzureAISearchIndex, reader.getString()); + } else if ("version".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor() + .setVersion(deserializedManagedAzureAISearchIndex, reader.getString()); + } else if ("id".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor() + .setId(deserializedManagedAzureAISearchIndex, reader.getString()); + } else if ("description".equals(fieldName)) { + JsonMergePatchHelper.getIndexAccessor() + .setDescription(deserializedManagedAzureAISearchIndex, reader.getString()); + } else if ("tags".equals(fieldName)) { + Map tags = reader.readMap(reader1 -> reader1.getString()); + JsonMergePatchHelper.getIndexAccessor().setTags(deserializedManagedAzureAISearchIndex, tags); + } else if ("type".equals(fieldName)) { + deserializedManagedAzureAISearchIndex.type = IndexType.fromString(reader.getString()); + } else if ("vectorStoreId".equals(fieldName)) { + deserializedManagedAzureAISearchIndex.vectorStoreId = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedManagedAzureAISearchIndex; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ModelDeployment.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ModelDeployment.java new file mode 100644 index 000000000000..18b971f10c64 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/ModelDeployment.java @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.Map; + +/** + * Model Deployment Definition. + */ +@Immutable +public final class ModelDeployment extends Deployment { + + /* + * The type of the deployment + */ + @Generated + private DeploymentType type = DeploymentType.MODEL_DEPLOYMENT; + + /* + * Publisher-specific name of the deployed model + */ + @Generated + private String modelName; + + /* + * Publisher-specific version of the deployed model + */ + @Generated + private String modelVersion; + + /* + * Name of the deployed model's publisher + */ + @Generated + private String modelPublisher; + + /* + * Capabilities of deployed model + */ + @Generated + private Map capabilities; + + /* + * Sku of the model deployment + */ + @Generated + private Sku sku; + + /* + * Name of the connection the deployment comes from + */ + @Generated + private String connectionName; + + /** + * Creates an instance of ModelDeployment class. + */ + @Generated + private ModelDeployment() { + } + + /** + * Get the type property: The type of the deployment. + * + * @return the type value. + */ + @Generated + @Override + public DeploymentType getType() { + return this.type; + } + + /** + * Get the modelName property: Publisher-specific name of the deployed model. + * + * @return the modelName value. + */ + @Generated + public String getModelName() { + return this.modelName; + } + + /** + * Get the modelVersion property: Publisher-specific version of the deployed model. + * + * @return the modelVersion value. + */ + @Generated + public String getModelVersion() { + return this.modelVersion; + } + + /** + * Get the modelPublisher property: Name of the deployed model's publisher. + * + * @return the modelPublisher value. + */ + @Generated + public String getModelPublisher() { + return this.modelPublisher; + } + + /** + * Get the capabilities property: Capabilities of deployed model. + * + * @return the capabilities value. + */ + @Generated + public Map getCapabilities() { + return this.capabilities; + } + + /** + * Get the sku property: Sku of the model deployment. + * + * @return the sku value. + */ + @Generated + public Sku getSku() { + return this.sku; + } + + /** + * Get the connectionName property: Name of the connection the deployment comes from. + * + * @return the connectionName value. + */ + @Generated + public String getConnectionName() { + return this.connectionName; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ModelDeployment from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ModelDeployment if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the ModelDeployment. + */ + @Generated + public static ModelDeployment fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ModelDeployment deserializedModelDeployment = new ModelDeployment(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("name".equals(fieldName)) { + deserializedModelDeployment.setName(reader.getString()); + } else if ("modelName".equals(fieldName)) { + deserializedModelDeployment.modelName = reader.getString(); + } else if ("modelVersion".equals(fieldName)) { + deserializedModelDeployment.modelVersion = reader.getString(); + } else if ("modelPublisher".equals(fieldName)) { + deserializedModelDeployment.modelPublisher = reader.getString(); + } else if ("capabilities".equals(fieldName)) { + Map capabilities = reader.readMap(reader1 -> reader1.getString()); + deserializedModelDeployment.capabilities = capabilities; + } else if ("sku".equals(fieldName)) { + deserializedModelDeployment.sku = Sku.fromJson(reader); + } else if ("type".equals(fieldName)) { + deserializedModelDeployment.type = DeploymentType.fromString(reader.getString()); + } else if ("connectionName".equals(fieldName)) { + deserializedModelDeployment.connectionName = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedModelDeployment; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/NoAuthenticationCredentials.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/NoAuthenticationCredentials.java new file mode 100644 index 000000000000..e105b393f993 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/NoAuthenticationCredentials.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Credentials that do not require authentication. + */ +@Immutable +public final class NoAuthenticationCredentials extends BaseCredentials { + + /* + * The type of credential used by the connection + */ + @Generated + private CredentialType type = CredentialType.NONE; + + /** + * Creates an instance of NoAuthenticationCredentials class. + */ + @Generated + private NoAuthenticationCredentials() { + } + + /** + * Get the type property: The type of credential used by the connection. + * + * @return the type value. + */ + @Generated + @Override + public CredentialType getType() { + return this.type; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of NoAuthenticationCredentials from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NoAuthenticationCredentials if the JsonReader was pointing to an instance of it, or null + * if it was pointing to JSON null. + * @throws IOException If an error occurs while reading the NoAuthenticationCredentials. + */ + @Generated + public static NoAuthenticationCredentials fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NoAuthenticationCredentials deserializedNoAuthenticationCredentials = new NoAuthenticationCredentials(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedNoAuthenticationCredentials.type = CredentialType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + return deserializedNoAuthenticationCredentials; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/PendingUploadRequest.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/PendingUploadRequest.java new file mode 100644 index 000000000000..dc7bdf306b69 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/PendingUploadRequest.java @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Represents a request for a pending upload. + */ +@Fluent +public final class PendingUploadRequest implements JsonSerializable { + + /* + * If PendingUploadId is not provided, a random GUID will be used. + */ + @Generated + private String pendingUploadId; + + /* + * Azure Storage Account connection name to use for generating temporary SAS token + */ + @Generated + private String connectionName; + + /* + * BlobReference is the only supported type. + */ + @Generated + private final PendingUploadType pendingUploadType = PendingUploadType.BLOB_REFERENCE; + + /** + * Creates an instance of PendingUploadRequest class. + */ + @Generated + public PendingUploadRequest() { + } + + /** + * Get the pendingUploadId property: If PendingUploadId is not provided, a random GUID will be used. + * + * @return the pendingUploadId value. + */ + @Generated + public String getPendingUploadId() { + return this.pendingUploadId; + } + + /** + * Set the pendingUploadId property: If PendingUploadId is not provided, a random GUID will be used. + * + * @param pendingUploadId the pendingUploadId value to set. + * @return the PendingUploadRequest object itself. + */ + @Generated + public PendingUploadRequest setPendingUploadId(String pendingUploadId) { + this.pendingUploadId = pendingUploadId; + return this; + } + + /** + * Get the connectionName property: Azure Storage Account connection name to use for generating temporary SAS token. + * + * @return the connectionName value. + */ + @Generated + public String getConnectionName() { + return this.connectionName; + } + + /** + * Set the connectionName property: Azure Storage Account connection name to use for generating temporary SAS token. + * + * @param connectionName the connectionName value to set. + * @return the PendingUploadRequest object itself. + */ + @Generated + public PendingUploadRequest setConnectionName(String connectionName) { + this.connectionName = connectionName; + return this; + } + + /** + * Get the pendingUploadType property: BlobReference is the only supported type. + * + * @return the pendingUploadType value. + */ + @Generated + public PendingUploadType getPendingUploadType() { + return this.pendingUploadType; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("pendingUploadType", + this.pendingUploadType == null ? null : this.pendingUploadType.toString()); + jsonWriter.writeStringField("pendingUploadId", this.pendingUploadId); + jsonWriter.writeStringField("connectionName", this.connectionName); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PendingUploadRequest from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PendingUploadRequest if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the PendingUploadRequest. + */ + @Generated + public static PendingUploadRequest fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + PendingUploadRequest deserializedPendingUploadRequest = new PendingUploadRequest(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("pendingUploadId".equals(fieldName)) { + deserializedPendingUploadRequest.pendingUploadId = reader.getString(); + } else if ("connectionName".equals(fieldName)) { + deserializedPendingUploadRequest.connectionName = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedPendingUploadRequest; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/PendingUploadResponse.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/PendingUploadResponse.java new file mode 100644 index 000000000000..985c8583d67c --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/PendingUploadResponse.java @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Represents the response for a pending upload request. + */ +@Immutable +public final class PendingUploadResponse implements JsonSerializable { + + /* + * Container-level read, write, list SAS. + */ + @Generated + private final BlobReference blobReference; + + /* + * ID for this upload request. + */ + @Generated + private final String pendingUploadId; + + /* + * Version of asset to be created if user did not specify version when initially creating upload + */ + @Generated + private String version; + + /* + * BlobReference is the only supported type + */ + @Generated + private final PendingUploadType pendingUploadType = PendingUploadType.BLOB_REFERENCE; + + /** + * Creates an instance of PendingUploadResponse class. + * + * @param blobReference the blobReference value to set. + * @param pendingUploadId the pendingUploadId value to set. + */ + @Generated + private PendingUploadResponse(BlobReference blobReference, String pendingUploadId) { + this.blobReference = blobReference; + this.pendingUploadId = pendingUploadId; + } + + /** + * Get the blobReference property: Container-level read, write, list SAS. + * + * @return the blobReference value. + */ + @Generated + public BlobReference getBlobReference() { + return this.blobReference; + } + + /** + * Get the pendingUploadId property: ID for this upload request. + * + * @return the pendingUploadId value. + */ + @Generated + public String getPendingUploadId() { + return this.pendingUploadId; + } + + /** + * Get the version property: Version of asset to be created if user did not specify version when initially creating + * upload. + * + * @return the version value. + */ + @Generated + public String getVersion() { + return this.version; + } + + /** + * Get the pendingUploadType property: BlobReference is the only supported type. + * + * @return the pendingUploadType value. + */ + @Generated + public PendingUploadType getPendingUploadType() { + return this.pendingUploadType; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("blobReference", this.blobReference); + jsonWriter.writeStringField("pendingUploadId", this.pendingUploadId); + jsonWriter.writeStringField("pendingUploadType", + this.pendingUploadType == null ? null : this.pendingUploadType.toString()); + jsonWriter.writeStringField("version", this.version); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of PendingUploadResponse from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of PendingUploadResponse if the JsonReader was pointing to an instance of it, or null if it + * was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the PendingUploadResponse. + */ + @Generated + public static PendingUploadResponse fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + BlobReference blobReference = null; + String pendingUploadId = null; + String version = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("blobReference".equals(fieldName)) { + blobReference = BlobReference.fromJson(reader); + } else if ("pendingUploadId".equals(fieldName)) { + pendingUploadId = reader.getString(); + } else if ("version".equals(fieldName)) { + version = reader.getString(); + } else { + reader.skipChildren(); + } + } + PendingUploadResponse deserializedPendingUploadResponse + = new PendingUploadResponse(blobReference, pendingUploadId); + deserializedPendingUploadResponse.version = version; + return deserializedPendingUploadResponse; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/PendingUploadType.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/PendingUploadType.java new file mode 100644 index 000000000000..70a7e30e1e99 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/PendingUploadType.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type of pending upload. + */ +public final class PendingUploadType extends ExpandableStringEnum { + + /** + * No pending upload. + */ + @Generated + public static final PendingUploadType NONE = fromString("None"); + + /** + * Blob Reference is the only supported type. + */ + @Generated + public static final PendingUploadType BLOB_REFERENCE = fromString("BlobReference"); + + /** + * Creates a new instance of PendingUploadType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public PendingUploadType() { + } + + /** + * Creates or finds a PendingUploadType from its string representation. + * + * @param name a name to look for. + * @return the corresponding PendingUploadType. + */ + @Generated + public static PendingUploadType fromString(String name) { + return fromString(name, PendingUploadType.class); + } + + /** + * Gets known PendingUploadType values. + * + * @return known PendingUploadType values. + */ + @Generated + public static Collection values() { + return values(PendingUploadType.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/RedTeam.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/RedTeam.java new file mode 100644 index 000000000000..6f4c47c64c8a --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/RedTeam.java @@ -0,0 +1,398 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.annotation.Generated; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * Red team details. + */ +@Fluent +public final class RedTeam implements JsonSerializable { + + /* + * Identifier of the red team run. + */ + @Generated + private String name; + + /* + * Name of the red-team run. + */ + @Generated + private String displayName; + + /* + * Number of simulation rounds. + */ + @Generated + private Integer numTurns; + + /* + * List of attack strategies or nested lists of attack strategies. + */ + @Generated + private List attackStrategies; + + /* + * Simulation-only or Simulation + Evaluation. Default false, if true the scan outputs conversation not evaluation + * result. + */ + @Generated + private Boolean simulationOnly; + + /* + * List of risk categories to generate attack objectives for. + */ + @Generated + private List riskCategories; + + /* + * Application scenario for the red team operation, to generate scenario specific attacks. + */ + @Generated + private String applicationScenario; + + /* + * Red team's tags. Unlike properties, tags are fully mutable. + */ + @Generated + private Map tags; + + /* + * Red team's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + */ + @Generated + private Map properties; + + /* + * Status of the red-team. It is set by service and is read-only. + */ + @Generated + private String status; + + /* + * Target configuration for the red-team run. + */ + @Generated + private final TargetConfig target; + + /** + * Creates an instance of RedTeam class. + * + * @param target the target value to set. + */ + @Generated + public RedTeam(TargetConfig target) { + this.target = target; + } + + /** + * Get the name property: Identifier of the red team run. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the displayName property: Name of the red-team run. + * + * @return the displayName value. + */ + @Generated + public String getDisplayName() { + return this.displayName; + } + + /** + * Set the displayName property: Name of the red-team run. + * + * @param displayName the displayName value to set. + * @return the RedTeam object itself. + */ + @Generated + public RedTeam setDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get the numTurns property: Number of simulation rounds. + * + * @return the numTurns value. + */ + @Generated + public Integer getNumTurns() { + return this.numTurns; + } + + /** + * Set the numTurns property: Number of simulation rounds. + * + * @param numTurns the numTurns value to set. + * @return the RedTeam object itself. + */ + @Generated + public RedTeam setNumTurns(Integer numTurns) { + this.numTurns = numTurns; + return this; + } + + /** + * Get the attackStrategies property: List of attack strategies or nested lists of attack strategies. + * + * @return the attackStrategies value. + */ + @Generated + public List getAttackStrategies() { + return this.attackStrategies; + } + + /** + * Set the attackStrategies property: List of attack strategies or nested lists of attack strategies. + * + * @param attackStrategies the attackStrategies value to set. + * @return the RedTeam object itself. + */ + @Generated + public RedTeam setAttackStrategies(List attackStrategies) { + this.attackStrategies = attackStrategies; + return this; + } + + /** + * Get the simulationOnly property: Simulation-only or Simulation + Evaluation. Default false, if true the scan + * outputs conversation not evaluation result. + * + * @return the simulationOnly value. + */ + @Generated + public Boolean isSimulationOnly() { + return this.simulationOnly; + } + + /** + * Set the simulationOnly property: Simulation-only or Simulation + Evaluation. Default false, if true the scan + * outputs conversation not evaluation result. + * + * @param simulationOnly the simulationOnly value to set. + * @return the RedTeam object itself. + */ + @Generated + public RedTeam setSimulationOnly(Boolean simulationOnly) { + this.simulationOnly = simulationOnly; + return this; + } + + /** + * Get the riskCategories property: List of risk categories to generate attack objectives for. + * + * @return the riskCategories value. + */ + @Generated + public List getRiskCategories() { + return this.riskCategories; + } + + /** + * Set the riskCategories property: List of risk categories to generate attack objectives for. + * + * @param riskCategories the riskCategories value to set. + * @return the RedTeam object itself. + */ + @Generated + public RedTeam setRiskCategories(List riskCategories) { + this.riskCategories = riskCategories; + return this; + } + + /** + * Get the applicationScenario property: Application scenario for the red team operation, to generate scenario + * specific attacks. + * + * @return the applicationScenario value. + */ + @Generated + public String getApplicationScenario() { + return this.applicationScenario; + } + + /** + * Set the applicationScenario property: Application scenario for the red team operation, to generate scenario + * specific attacks. + * + * @param applicationScenario the applicationScenario value to set. + * @return the RedTeam object itself. + */ + @Generated + public RedTeam setApplicationScenario(String applicationScenario) { + this.applicationScenario = applicationScenario; + return this; + } + + /** + * Get the tags property: Red team's tags. Unlike properties, tags are fully mutable. + * + * @return the tags value. + */ + @Generated + public Map getTags() { + return this.tags; + } + + /** + * Set the tags property: Red team's tags. Unlike properties, tags are fully mutable. + * + * @param tags the tags value to set. + * @return the RedTeam object itself. + */ + @Generated + public RedTeam setTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get the properties property: Red team's properties. Unlike tags, properties are add-only. Once added, a property + * cannot be removed. + * + * @return the properties value. + */ + @Generated + public Map getProperties() { + return this.properties; + } + + /** + * Set the properties property: Red team's properties. Unlike tags, properties are add-only. Once added, a property + * cannot be removed. + * + * @param properties the properties value to set. + * @return the RedTeam object itself. + */ + @Generated + public RedTeam setProperties(Map properties) { + this.properties = properties; + return this; + } + + /** + * Get the status property: Status of the red-team. It is set by service and is read-only. + * + * @return the status value. + */ + @Generated + public String getStatus() { + return this.status; + } + + /** + * Get the target property: Target configuration for the red-team run. + * + * @return the target value. + */ + @Generated + public TargetConfig getTarget() { + return this.target; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("target", this.target); + jsonWriter.writeStringField("displayName", this.displayName); + jsonWriter.writeNumberField("numTurns", this.numTurns); + jsonWriter.writeArrayField("attackStrategies", this.attackStrategies, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeBooleanField("simulationOnly", this.simulationOnly); + jsonWriter.writeArrayField("riskCategories", this.riskCategories, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeStringField("applicationScenario", this.applicationScenario); + jsonWriter.writeMapField("tags", this.tags, (writer, element) -> writer.writeString(element)); + jsonWriter.writeMapField("properties", this.properties, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of RedTeam from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of RedTeam if the JsonReader was pointing to an instance of it, or null if it was pointing to + * JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the RedTeam. + */ + @Generated + public static RedTeam fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String name = null; + TargetConfig target = null; + String displayName = null; + Integer numTurns = null; + List attackStrategies = null; + Boolean simulationOnly = null; + List riskCategories = null; + String applicationScenario = null; + Map tags = null; + Map properties = null; + String status = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("id".equals(fieldName)) { + name = reader.getString(); + } else if ("target".equals(fieldName)) { + target = TargetConfig.fromJson(reader); + } else if ("displayName".equals(fieldName)) { + displayName = reader.getString(); + } else if ("numTurns".equals(fieldName)) { + numTurns = reader.getNullable(JsonReader::getInt); + } else if ("attackStrategies".equals(fieldName)) { + attackStrategies = reader.readArray(reader1 -> AttackStrategy.fromString(reader1.getString())); + } else if ("simulationOnly".equals(fieldName)) { + simulationOnly = reader.getNullable(JsonReader::getBoolean); + } else if ("riskCategories".equals(fieldName)) { + riskCategories = reader.readArray(reader1 -> RiskCategory.fromString(reader1.getString())); + } else if ("applicationScenario".equals(fieldName)) { + applicationScenario = reader.getString(); + } else if ("tags".equals(fieldName)) { + tags = reader.readMap(reader1 -> reader1.getString()); + } else if ("properties".equals(fieldName)) { + properties = reader.readMap(reader1 -> reader1.getString()); + } else if ("status".equals(fieldName)) { + status = reader.getString(); + } else { + reader.skipChildren(); + } + } + RedTeam deserializedRedTeam = new RedTeam(target); + deserializedRedTeam.name = name; + deserializedRedTeam.displayName = displayName; + deserializedRedTeam.numTurns = numTurns; + deserializedRedTeam.attackStrategies = attackStrategies; + deserializedRedTeam.simulationOnly = simulationOnly; + deserializedRedTeam.riskCategories = riskCategories; + deserializedRedTeam.applicationScenario = applicationScenario; + deserializedRedTeam.tags = tags; + deserializedRedTeam.properties = properties; + deserializedRedTeam.status = status; + return deserializedRedTeam; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/RiskCategory.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/RiskCategory.java new file mode 100644 index 000000000000..6fc56ca8b46f --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/RiskCategory.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Risk category for the attack objective. + */ +public final class RiskCategory extends ExpandableStringEnum { + + /** + * Represents content related to hate or unfairness. + */ + @Generated + public static final RiskCategory HATE_UNFAIRNESS = fromString("HateUnfairness"); + + /** + * Represents content related to violence. + */ + @Generated + public static final RiskCategory VIOLENCE = fromString("Violence"); + + /** + * Represents content of a sexual nature. + */ + @Generated + public static final RiskCategory SEXUAL = fromString("Sexual"); + + /** + * Represents content related to self-harm. + */ + @Generated + public static final RiskCategory SELF_HARM = fromString("SelfHarm"); + + /** + * Creates a new instance of RiskCategory value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public RiskCategory() { + } + + /** + * Creates or finds a RiskCategory from its string representation. + * + * @param name a name to look for. + * @return the corresponding RiskCategory. + */ + @Generated + public static RiskCategory fromString(String name) { + return fromString(name, RiskCategory.class); + } + + /** + * Gets known RiskCategory values. + * + * @return known RiskCategory values. + */ + @Generated + public static Collection values() { + return values(RiskCategory.class); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/SasCredential.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/SasCredential.java new file mode 100644 index 000000000000..91b4fbb35956 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/SasCredential.java @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * SAS Credential definition. + */ +@Immutable +public final class SasCredential implements JsonSerializable { + + /* + * SAS uri + */ + @Generated + private String sasUri; + + /* + * Type of credential + */ + @Generated + private final String type = "SAS"; + + /** + * Creates an instance of SasCredential class. + */ + @Generated + private SasCredential() { + } + + /** + * Get the sasUri property: SAS uri. + * + * @return the sasUri value. + */ + @Generated + public String getSasUri() { + return this.sasUri; + } + + /** + * Get the type property: Type of credential. + * + * @return the type value. + */ + @Generated + public String getType() { + return this.type; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SasCredential from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SasCredential if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the SasCredential. + */ + @Generated + public static SasCredential fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SasCredential deserializedSasCredential = new SasCredential(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("sasUri".equals(fieldName)) { + deserializedSasCredential.sasUri = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedSasCredential; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/SasCredentials.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/SasCredentials.java new file mode 100644 index 000000000000..a915c5df1a26 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/SasCredentials.java @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Shared Access Signature (SAS) credential definition. + */ +@Immutable +public final class SasCredentials extends BaseCredentials { + + /* + * The type of credential used by the connection + */ + @Generated + private CredentialType type = CredentialType.SAS; + + /* + * SAS token + */ + @Generated + private String sasToken; + + /** + * Creates an instance of SasCredentials class. + */ + @Generated + private SasCredentials() { + } + + /** + * Get the type property: The type of credential used by the connection. + * + * @return the type value. + */ + @Generated + @Override + public CredentialType getType() { + return this.type; + } + + /** + * Get the sasToken property: SAS token. + * + * @return the sasToken value. + */ + @Generated + public String getSasToken() { + return this.sasToken; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SasCredentials from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SasCredentials if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the SasCredentials. + */ + @Generated + public static SasCredentials fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SasCredentials deserializedSasCredentials = new SasCredentials(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedSasCredentials.type = CredentialType.fromString(reader.getString()); + } else if ("SAS".equals(fieldName)) { + deserializedSasCredentials.sasToken = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedSasCredentials; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Sku.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Sku.java new file mode 100644 index 000000000000..323ea06a6fd1 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/Sku.java @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Sku information. + */ +@Immutable +public final class Sku implements JsonSerializable { + + /* + * Sku capacity + */ + @Generated + private final long capacity; + + /* + * Sku family + */ + @Generated + private final String family; + + /* + * Sku name + */ + @Generated + private final String name; + + /* + * Sku size + */ + @Generated + private final String size; + + /* + * Sku tier + */ + @Generated + private final String tier; + + /** + * Creates an instance of Sku class. + * + * @param capacity the capacity value to set. + * @param family the family value to set. + * @param name the name value to set. + * @param size the size value to set. + * @param tier the tier value to set. + */ + @Generated + private Sku(long capacity, String family, String name, String size, String tier) { + this.capacity = capacity; + this.family = family; + this.name = name; + this.size = size; + this.tier = tier; + } + + /** + * Get the capacity property: Sku capacity. + * + * @return the capacity value. + */ + @Generated + public long getCapacity() { + return this.capacity; + } + + /** + * Get the family property: Sku family. + * + * @return the family value. + */ + @Generated + public String getFamily() { + return this.family; + } + + /** + * Get the name property: Sku name. + * + * @return the name value. + */ + @Generated + public String getName() { + return this.name; + } + + /** + * Get the size property: Sku size. + * + * @return the size value. + */ + @Generated + public String getSize() { + return this.size; + } + + /** + * Get the tier property: Sku tier. + * + * @return the tier value. + */ + @Generated + public String getTier() { + return this.tier; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeLongField("capacity", this.capacity); + jsonWriter.writeStringField("family", this.family); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("size", this.size); + jsonWriter.writeStringField("tier", this.tier); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Sku from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Sku if the JsonReader was pointing to an instance of it, or null if it was pointing to + * JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the Sku. + */ + @Generated + public static Sku fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + long capacity = 0L; + String family = null; + String name = null; + String size = null; + String tier = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("capacity".equals(fieldName)) { + capacity = reader.getLong(); + } else if ("family".equals(fieldName)) { + family = reader.getString(); + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("size".equals(fieldName)) { + size = reader.getString(); + } else if ("tier".equals(fieldName)) { + tier = reader.getString(); + } else { + reader.skipChildren(); + } + } + return new Sku(capacity, family, name, size, tier); + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/TargetConfig.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/TargetConfig.java new file mode 100644 index 000000000000..a131dddf51d2 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/TargetConfig.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.ai.projects.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.Immutable; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Abstract class for target configuration. + */ +@Immutable +public class TargetConfig implements JsonSerializable { + + /* + * Type of the model configuration. + */ + @Generated + private String type = "TargetConfig"; + + /** + * Creates an instance of TargetConfig class. + */ + @Generated + public TargetConfig() { + } + + /** + * Get the type property: Type of the model configuration. + * + * @return the type value. + */ + @Generated + public String getType() { + return this.type; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of TargetConfig from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of TargetConfig if the JsonReader was pointing to an instance of it, or null if it was + * pointing to JSON null. + * @throws IOException If an error occurs while reading the TargetConfig. + */ + @Generated + public static TargetConfig fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + // Prepare for reading + readerToUse.nextToken(); + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("AzureOpenAIModel".equals(discriminatorValue)) { + return AzureOpenAIModelConfiguration.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + @Generated + static TargetConfig fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + TargetConfig deserializedTargetConfig = new TargetConfig(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("type".equals(fieldName)) { + deserializedTargetConfig.type = reader.getString(); + } else { + reader.skipChildren(); + } + } + return deserializedTargetConfig; + }); + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/package-info.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/package-info.java new file mode 100644 index 000000000000..9fa6fc53dccd --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/models/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +/** + * + * Package containing the data models for Projects. + * + */ +package com.azure.ai.projects.models; diff --git a/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/package-info.java b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/package-info.java new file mode 100644 index 000000000000..bfd5e37d8633 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/com/azure/ai/projects/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. +/** + * + * Package containing the classes for Projects. + * + */ +package com.azure.ai.projects; diff --git a/sdk/ai/azure-ai-projects/src/main/java/module-info.java b/sdk/ai/azure-ai-projects/src/main/java/module-info.java new file mode 100644 index 000000000000..5e84dd853e1a --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/java/module-info.java @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +module com.azure.ai.projects { + requires transitive com.azure.core; + requires com.azure.storage.blob; + requires com.azure.ai.agents.persistent; + requires com.azure.ai.inference; + + exports com.azure.ai.projects; + exports com.azure.ai.projects.models; + + opens com.azure.ai.projects.models to com.azure.core; +} diff --git a/sdk/ai/azure-ai-projects/src/main/resources/META-INF/azure-ai-projects_apiview_properties.json b/sdk/ai/azure-ai-projects/src/main/resources/META-INF/azure-ai-projects_apiview_properties.json new file mode 100644 index 000000000000..3840380142b7 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/resources/META-INF/azure-ai-projects_apiview_properties.json @@ -0,0 +1,142 @@ +{ + "flavor": "azure", + "CrossLanguageDefinitionId": { + "com.azure.ai.projects.AIProjectClientBuilder": "Azure.AI.Projects", + "com.azure.ai.projects.ConnectionsAsyncClient": "Azure.AI.Projects.Connections", + "com.azure.ai.projects.ConnectionsAsyncClient.getConnection": "Azure.AI.Projects.Connections.get", + "com.azure.ai.projects.ConnectionsAsyncClient.getConnectionWithCredentials": "Azure.AI.Projects.Connections.getWithCredentials", + "com.azure.ai.projects.ConnectionsAsyncClient.getConnectionWithCredentialsWithResponse": "Azure.AI.Projects.Connections.getWithCredentials", + "com.azure.ai.projects.ConnectionsAsyncClient.getConnectionWithResponse": "Azure.AI.Projects.Connections.get", + "com.azure.ai.projects.ConnectionsAsyncClient.listConnections": "Azure.AI.Projects.Connections.list", + "com.azure.ai.projects.ConnectionsClient": "Azure.AI.Projects.Connections", + "com.azure.ai.projects.ConnectionsClient.getConnection": "Azure.AI.Projects.Connections.get", + "com.azure.ai.projects.ConnectionsClient.getConnectionWithCredentials": "Azure.AI.Projects.Connections.getWithCredentials", + "com.azure.ai.projects.ConnectionsClient.getConnectionWithCredentialsWithResponse": "Azure.AI.Projects.Connections.getWithCredentials", + "com.azure.ai.projects.ConnectionsClient.getConnectionWithResponse": "Azure.AI.Projects.Connections.get", + "com.azure.ai.projects.ConnectionsClient.listConnections": "Azure.AI.Projects.Connections.list", + "com.azure.ai.projects.DatasetsAsyncClient": "Azure.AI.Projects.Datasets", + "com.azure.ai.projects.DatasetsAsyncClient.createOrUpdateDatasetVersion": "Azure.AI.Projects.ServicePatterns.Datasets.createOrUpdateVersion", + "com.azure.ai.projects.DatasetsAsyncClient.createOrUpdateDatasetVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Datasets.createOrUpdateVersion", + "com.azure.ai.projects.DatasetsAsyncClient.deleteDatasetVersion": "Azure.AI.Projects.ServicePatterns.Datasets.deleteVersion", + "com.azure.ai.projects.DatasetsAsyncClient.deleteDatasetVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Datasets.deleteVersion", + "com.azure.ai.projects.DatasetsAsyncClient.getCredentials": "Azure.AI.Projects.Datasets.getCredentials", + "com.azure.ai.projects.DatasetsAsyncClient.getCredentialsWithResponse": "Azure.AI.Projects.Datasets.getCredentials", + "com.azure.ai.projects.DatasetsAsyncClient.getDatasetVersion": "Azure.AI.Projects.ServicePatterns.Datasets.getVersion", + "com.azure.ai.projects.DatasetsAsyncClient.getDatasetVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Datasets.getVersion", + "com.azure.ai.projects.DatasetsAsyncClient.listDatasetVersions": "Azure.AI.Projects.ServicePatterns.Datasets.listVersions", + "com.azure.ai.projects.DatasetsAsyncClient.listLatestDatasetVersions": "Azure.AI.Projects.ServicePatterns.Datasets.listLatest", + "com.azure.ai.projects.DatasetsAsyncClient.pendingUpload": "Azure.AI.Projects.Datasets.startPendingUploadVersion", + "com.azure.ai.projects.DatasetsAsyncClient.pendingUploadWithResponse": "Azure.AI.Projects.Datasets.startPendingUploadVersion", + "com.azure.ai.projects.DatasetsClient": "Azure.AI.Projects.Datasets", + "com.azure.ai.projects.DatasetsClient.createOrUpdateDatasetVersion": "Azure.AI.Projects.ServicePatterns.Datasets.createOrUpdateVersion", + "com.azure.ai.projects.DatasetsClient.createOrUpdateDatasetVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Datasets.createOrUpdateVersion", + "com.azure.ai.projects.DatasetsClient.deleteDatasetVersion": "Azure.AI.Projects.ServicePatterns.Datasets.deleteVersion", + "com.azure.ai.projects.DatasetsClient.deleteDatasetVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Datasets.deleteVersion", + "com.azure.ai.projects.DatasetsClient.getCredentials": "Azure.AI.Projects.Datasets.getCredentials", + "com.azure.ai.projects.DatasetsClient.getCredentialsWithResponse": "Azure.AI.Projects.Datasets.getCredentials", + "com.azure.ai.projects.DatasetsClient.getDatasetVersion": "Azure.AI.Projects.ServicePatterns.Datasets.getVersion", + "com.azure.ai.projects.DatasetsClient.getDatasetVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Datasets.getVersion", + "com.azure.ai.projects.DatasetsClient.listDatasetVersions": "Azure.AI.Projects.ServicePatterns.Datasets.listVersions", + "com.azure.ai.projects.DatasetsClient.listLatestDatasetVersions": "Azure.AI.Projects.ServicePatterns.Datasets.listLatest", + "com.azure.ai.projects.DatasetsClient.pendingUpload": "Azure.AI.Projects.Datasets.startPendingUploadVersion", + "com.azure.ai.projects.DatasetsClient.pendingUploadWithResponse": "Azure.AI.Projects.Datasets.startPendingUploadVersion", + "com.azure.ai.projects.DeploymentsAsyncClient": "Azure.AI.Projects.Deployments", + "com.azure.ai.projects.DeploymentsAsyncClient.getDeployment": "Azure.AI.Projects.Deployments.get", + "com.azure.ai.projects.DeploymentsAsyncClient.getDeploymentWithResponse": "Azure.AI.Projects.Deployments.get", + "com.azure.ai.projects.DeploymentsAsyncClient.listDeployments": "Azure.AI.Projects.Deployments.list", + "com.azure.ai.projects.DeploymentsClient": "Azure.AI.Projects.Deployments", + "com.azure.ai.projects.DeploymentsClient.getDeployment": "Azure.AI.Projects.Deployments.get", + "com.azure.ai.projects.DeploymentsClient.getDeploymentWithResponse": "Azure.AI.Projects.Deployments.get", + "com.azure.ai.projects.DeploymentsClient.listDeployments": "Azure.AI.Projects.Deployments.list", + "com.azure.ai.projects.EvaluationsAsyncClient": "Azure.AI.Projects.Evaluations", + "com.azure.ai.projects.EvaluationsAsyncClient.createAgentEvaluation": "Azure.AI.Projects.Evaluations.createAgentEvaluation", + "com.azure.ai.projects.EvaluationsAsyncClient.createAgentEvaluationWithResponse": "Azure.AI.Projects.Evaluations.createAgentEvaluation", + "com.azure.ai.projects.EvaluationsAsyncClient.createEvaluation": "Azure.AI.Projects.Evaluations.create", + "com.azure.ai.projects.EvaluationsAsyncClient.createEvaluationWithResponse": "Azure.AI.Projects.Evaluations.create", + "com.azure.ai.projects.EvaluationsAsyncClient.getEvaluation": "Azure.AI.Projects.Evaluations.get", + "com.azure.ai.projects.EvaluationsAsyncClient.getEvaluationWithResponse": "Azure.AI.Projects.Evaluations.get", + "com.azure.ai.projects.EvaluationsAsyncClient.listEvaluations": "Azure.AI.Projects.Evaluations.list", + "com.azure.ai.projects.EvaluationsClient": "Azure.AI.Projects.Evaluations", + "com.azure.ai.projects.EvaluationsClient.createAgentEvaluation": "Azure.AI.Projects.Evaluations.createAgentEvaluation", + "com.azure.ai.projects.EvaluationsClient.createAgentEvaluationWithResponse": "Azure.AI.Projects.Evaluations.createAgentEvaluation", + "com.azure.ai.projects.EvaluationsClient.createEvaluation": "Azure.AI.Projects.Evaluations.create", + "com.azure.ai.projects.EvaluationsClient.createEvaluationWithResponse": "Azure.AI.Projects.Evaluations.create", + "com.azure.ai.projects.EvaluationsClient.getEvaluation": "Azure.AI.Projects.Evaluations.get", + "com.azure.ai.projects.EvaluationsClient.getEvaluationWithResponse": "Azure.AI.Projects.Evaluations.get", + "com.azure.ai.projects.EvaluationsClient.listEvaluations": "Azure.AI.Projects.Evaluations.list", + "com.azure.ai.projects.IndexesAsyncClient": "Azure.AI.Projects.Indexes", + "com.azure.ai.projects.IndexesAsyncClient.createOrUpdateIndexVersion": "Azure.AI.Projects.ServicePatterns.Indexes.createOrUpdateVersion", + "com.azure.ai.projects.IndexesAsyncClient.createOrUpdateIndexVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Indexes.createOrUpdateVersion", + "com.azure.ai.projects.IndexesAsyncClient.deleteIndexVersion": "Azure.AI.Projects.ServicePatterns.Indexes.deleteVersion", + "com.azure.ai.projects.IndexesAsyncClient.deleteIndexVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Indexes.deleteVersion", + "com.azure.ai.projects.IndexesAsyncClient.getIndexVersion": "Azure.AI.Projects.ServicePatterns.Indexes.getVersion", + "com.azure.ai.projects.IndexesAsyncClient.getIndexVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Indexes.getVersion", + "com.azure.ai.projects.IndexesAsyncClient.listIndexVersions": "Azure.AI.Projects.ServicePatterns.Indexes.listVersions", + "com.azure.ai.projects.IndexesAsyncClient.listLatestIndexVersions": "Azure.AI.Projects.ServicePatterns.Indexes.listLatest", + "com.azure.ai.projects.IndexesClient": "Azure.AI.Projects.Indexes", + "com.azure.ai.projects.IndexesClient.createOrUpdateIndexVersion": "Azure.AI.Projects.ServicePatterns.Indexes.createOrUpdateVersion", + "com.azure.ai.projects.IndexesClient.createOrUpdateIndexVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Indexes.createOrUpdateVersion", + "com.azure.ai.projects.IndexesClient.deleteIndexVersion": "Azure.AI.Projects.ServicePatterns.Indexes.deleteVersion", + "com.azure.ai.projects.IndexesClient.deleteIndexVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Indexes.deleteVersion", + "com.azure.ai.projects.IndexesClient.getIndexVersion": "Azure.AI.Projects.ServicePatterns.Indexes.getVersion", + "com.azure.ai.projects.IndexesClient.getIndexVersionWithResponse": "Azure.AI.Projects.ServicePatterns.Indexes.getVersion", + "com.azure.ai.projects.IndexesClient.listIndexVersions": "Azure.AI.Projects.ServicePatterns.Indexes.listVersions", + "com.azure.ai.projects.IndexesClient.listLatestIndexVersions": "Azure.AI.Projects.ServicePatterns.Indexes.listLatest", + "com.azure.ai.projects.RedTeamsAsyncClient": "Azure.AI.Projects.RedTeams", + "com.azure.ai.projects.RedTeamsAsyncClient.createRedTeam": "Azure.AI.Projects.RedTeams.create", + "com.azure.ai.projects.RedTeamsAsyncClient.createRedTeamWithResponse": "Azure.AI.Projects.RedTeams.create", + "com.azure.ai.projects.RedTeamsAsyncClient.getRedTeam": "Azure.AI.Projects.RedTeams.get", + "com.azure.ai.projects.RedTeamsAsyncClient.getRedTeamWithResponse": "Azure.AI.Projects.RedTeams.get", + "com.azure.ai.projects.RedTeamsAsyncClient.listRedTeams": "Azure.AI.Projects.RedTeams.list", + "com.azure.ai.projects.RedTeamsClient": "Azure.AI.Projects.RedTeams", + "com.azure.ai.projects.RedTeamsClient.createRedTeam": "Azure.AI.Projects.RedTeams.create", + "com.azure.ai.projects.RedTeamsClient.createRedTeamWithResponse": "Azure.AI.Projects.RedTeams.create", + "com.azure.ai.projects.RedTeamsClient.getRedTeam": "Azure.AI.Projects.RedTeams.get", + "com.azure.ai.projects.RedTeamsClient.getRedTeamWithResponse": "Azure.AI.Projects.RedTeams.get", + "com.azure.ai.projects.RedTeamsClient.listRedTeams": "Azure.AI.Projects.RedTeams.list", + "com.azure.ai.projects.models.AgentEvaluation": "Azure.AI.Projects.AgentEvaluation", + "com.azure.ai.projects.models.AgentEvaluationRedactionConfiguration": "Azure.AI.Projects.AgentEvaluationRedactionConfiguration", + "com.azure.ai.projects.models.AgentEvaluationRequest": "Azure.AI.Projects.AgentEvaluationRequest", + "com.azure.ai.projects.models.AgentEvaluationResult": "Azure.AI.Projects.AgentEvaluationResult", + "com.azure.ai.projects.models.AgentEvaluationSamplingConfiguration": "Azure.AI.Projects.AgentEvaluationSamplingConfiguration", + "com.azure.ai.projects.models.ApiKeyCredentials": "Azure.AI.Projects.ApiKeyCredentials", + "com.azure.ai.projects.models.AssetCredentialResult": "Azure.AI.Projects.AssetCredentialResponse", + "com.azure.ai.projects.models.AttackStrategy": "Azure.AI.Projects.AttackStrategy", + "com.azure.ai.projects.models.AzureAISearchIndex": "Azure.AI.Projects.AzureAISearchIndex", + "com.azure.ai.projects.models.AzureOpenAIModelConfiguration": "Azure.AI.Projects.AzureOpenAIModelConfiguration", + "com.azure.ai.projects.models.BaseCredentials": "Azure.AI.Projects.BaseCredentials", + "com.azure.ai.projects.models.BlobReference": "Azure.AI.Projects.BlobReference", + "com.azure.ai.projects.models.Connection": "Azure.AI.Projects.Connection", + "com.azure.ai.projects.models.ConnectionType": "Azure.AI.Projects.ConnectionType", + "com.azure.ai.projects.models.CosmosDBIndex": "Azure.AI.Projects.CosmosDBIndex", + "com.azure.ai.projects.models.CredentialType": "Azure.AI.Projects.CredentialType", + "com.azure.ai.projects.models.CustomCredential": "Azure.AI.Projects.CustomCredential", + "com.azure.ai.projects.models.DatasetType": "Azure.AI.Projects.DatasetType", + "com.azure.ai.projects.models.DatasetVersion": "Azure.AI.Projects.DatasetVersion", + "com.azure.ai.projects.models.Deployment": "Azure.AI.Projects.Deployment", + "com.azure.ai.projects.models.DeploymentType": "Azure.AI.Projects.DeploymentType", + "com.azure.ai.projects.models.EmbeddingConfiguration": "Azure.AI.Projects.EmbeddingConfiguration", + "com.azure.ai.projects.models.EntraIDCredentials": "Azure.AI.Projects.EntraIDCredentials", + "com.azure.ai.projects.models.Evaluation": "Azure.AI.Projects.Evaluation", + "com.azure.ai.projects.models.EvaluatorConfiguration": "Azure.AI.Projects.EvaluatorConfiguration", + "com.azure.ai.projects.models.FieldMapping": "Azure.AI.Projects.FieldMapping", + "com.azure.ai.projects.models.FileDatasetVersion": "Azure.AI.Projects.FileDatasetVersion", + "com.azure.ai.projects.models.FolderDatasetVersion": "Azure.AI.Projects.FolderDatasetVersion", + "com.azure.ai.projects.models.Index": "Azure.AI.Projects.Index", + "com.azure.ai.projects.models.IndexType": "Azure.AI.Projects.IndexType", + "com.azure.ai.projects.models.InputData": "Azure.AI.Projects.InputData", + "com.azure.ai.projects.models.InputDataset": "Azure.AI.Projects.InputDataset", + "com.azure.ai.projects.models.ManagedAzureAISearchIndex": "Azure.AI.Projects.ManagedAzureAISearchIndex", + "com.azure.ai.projects.models.ModelDeployment": "Azure.AI.Projects.ModelDeployment", + "com.azure.ai.projects.models.NoAuthenticationCredentials": "Azure.AI.Projects.NoAuthenticationCredentials", + "com.azure.ai.projects.models.PendingUploadRequest": "Azure.AI.Projects.PendingUploadRequest", + "com.azure.ai.projects.models.PendingUploadResponse": "Azure.AI.Projects.PendingUploadResponse", + "com.azure.ai.projects.models.PendingUploadType": "Azure.AI.Projects.PendingUploadType", + "com.azure.ai.projects.models.RedTeam": "Azure.AI.Projects.RedTeam", + "com.azure.ai.projects.models.RiskCategory": "Azure.AI.Projects.RiskCategory", + "com.azure.ai.projects.models.SasCredential": "Azure.AI.Projects.SasCredential", + "com.azure.ai.projects.models.SasCredentials": "Azure.AI.Projects.SASCredentials", + "com.azure.ai.projects.models.Sku": "Azure.AI.Projects.Sku", + "com.azure.ai.projects.models.TargetConfig": "Azure.AI.Projects.TargetConfig" + } +} diff --git a/sdk/ai/azure-ai-projects/src/main/resources/azure-ai-projects.properties b/sdk/ai/azure-ai-projects/src/main/resources/azure-ai-projects.properties new file mode 100644 index 000000000000..ca812989b4f2 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/main/resources/azure-ai-projects.properties @@ -0,0 +1,2 @@ +name=${project.artifactId} +version=${project.version} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/AgentsAsyncSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/AgentsAsyncSample.java new file mode 100644 index 000000000000..11afc9f48919 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/AgentsAsyncSample.java @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.agents.persistent.AgentsServiceVersion; +import com.azure.ai.agents.persistent.PersistentAgentsAdministrationAsyncClient; +import com.azure.ai.agents.persistent.PersistentAgentsAdministrationClientBuilder; +import com.azure.ai.agents.persistent.models.AgentDeletionStatus; +import com.azure.ai.agents.persistent.models.CreateAgentOptions; +import com.azure.ai.agents.persistent.models.PersistentAgent; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import reactor.core.publisher.Mono; + +public class AgentsAsyncSample { + + private static PersistentAgentsAdministrationAsyncClient agentsAsyncClient + = new PersistentAgentsAdministrationClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .serviceVersion(AgentsServiceVersion.V2025_05_15_PREVIEW) + .buildAsyncClient(); + + public static void main(String[] args) { + // Using block() to wait for the async operations to complete in the sample + PersistentAgent createdAgent = createAgent().block(); + deleteAgent(createdAgent.getId()).block(); + } + + public static Mono createAgent() { + // BEGIN:com.azure.ai.projects.AgentsAsyncSample.createAgent + + String agentName = "basic_example"; + CreateAgentOptions createAgentOptions = new CreateAgentOptions("gpt-4o-mini") + .setName(agentName) + .setInstructions("You are a helpful agent"); + + return agentsAsyncClient.createAgent(createAgentOptions) + .doOnNext(agent -> System.out.println("Agent created: " + agent.getId())); + + // END:com.azure.ai.projects.AgentsAsyncSample.createAgent + } + + public static Mono deleteAgent(String agentId) { + // BEGIN:com.azure.ai.projects.AgentsAsyncSample.deleteAgent + + return agentsAsyncClient.deleteAgent(agentId) + .doOnNext(deletionStatus -> { + System.out.println("Agent: " + agentId); + System.out.println("Delete confirmation: " + deletionStatus.isDeleted()); + }); + + // END:com.azure.ai.projects.AgentsAsyncSample.deleteAgent + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/AgentsSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/AgentsSample.java new file mode 100644 index 000000000000..5b053aba6977 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/AgentsSample.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.agents.persistent.AgentsServiceVersion; +import com.azure.ai.agents.persistent.PersistentAgentsAdministrationClient; +import com.azure.ai.agents.persistent.PersistentAgentsAdministrationClientBuilder; +import com.azure.ai.agents.persistent.models.AgentDeletionStatus; +import com.azure.ai.agents.persistent.models.CreateAgentOptions; +import com.azure.ai.agents.persistent.models.PersistentAgent; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; + +public class AgentsSample { + + private static PersistentAgentsAdministrationClient agentsClient + = new PersistentAgentsAdministrationClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .serviceVersion(AgentsServiceVersion.V2025_05_15_PREVIEW) + .buildClient(); + + public static void main(String[] args) { + PersistentAgent createdAgent = createAgent(); + deleteAgent(createdAgent.getId()); + } + + public static PersistentAgent createAgent() { + // BEGIN:com.azure.ai.projects.AgentsSample.createAgent + + String agentName = "basic_example"; + CreateAgentOptions createAgentOptions = new CreateAgentOptions("gpt-4o-mini") + .setName(agentName) + .setInstructions("You are a helpful agent"); + PersistentAgent agent = agentsClient.createAgent(createAgentOptions); + System.out.println("Agent created: " + agent.getId()); + return agent; + + // END:com.azure.ai.projects.AgentsSample.createAgent + } + + public static void deleteAgent(String agentId) { + // BEGIN:com.azure.ai.projects.AgentsSample.deleteAgent + + AgentDeletionStatus deletionStatus = agentsClient.deleteAgent(agentId); + System.out.println("Agent: " + agentId); + System.out.println("Delete confirmation: " + deletionStatus.isDeleted()); + + // END:com.azure.ai.projects.AgentsSample.deleteAgent + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/ConnectionsAsyncSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/ConnectionsAsyncSample.java new file mode 100644 index 000000000000..d5920ed81910 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/ConnectionsAsyncSample.java @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.Connection; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class ConnectionsAsyncSample { + + private static ConnectionsAsyncClient connectionsAsyncClient + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildConnectionsAsyncClient(); + + public static void main(String[] args) { + // Using block() to wait for the async operations to complete in the sample + listConnections().blockLast(); + getConnectionWithoutCredentials().block(); + getConnectionWithCredentials().block(); + } + + public static Flux listConnections() { + // BEGIN:com.azure.ai.projects.ConnectionsAsyncSample.listConnections + + return connectionsAsyncClient.listConnections() + .doOnNext(connection -> System.out.printf("Connection name: %s%n", connection.getName())); + + // END:com.azure.ai.projects.ConnectionsAsyncSample.listConnections + } + + public static Mono getConnectionWithoutCredentials() { + // BEGIN:com.azure.ai.projects.ConnectionsAsyncSample.getConnectionWithoutCredentials + + String connectionName = Configuration.getGlobalConfiguration().get("TEST_CONNECTION_NAME", ""); + return connectionsAsyncClient.getConnection(connectionName) + .doOnNext(connection -> System.out.printf("Connection name: %s%n", connection.getName())); + + // END:com.azure.ai.projects.ConnectionsAsyncSample.getConnectionWithoutCredentials + } + + public static Mono getConnectionWithCredentials() { + // BEGIN:com.azure.ai.projects.ConnectionsAsyncSample.getConnectionWithCredentials + + String connectionName = Configuration.getGlobalConfiguration().get("TEST_CONNECTION_NAME", ""); + return connectionsAsyncClient.getConnectionWithCredentials(connectionName) + .doOnNext(connection -> { + System.out.printf("Connection name: %s%n", connection.getName()); + System.out.printf("Connection credentials: %s%n", connection.getCredentials().getType()); + }); + + // END:com.azure.ai.projects.ConnectionsAsyncSample.getConnectionWithCredentials + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/ConnectionsSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/ConnectionsSample.java new file mode 100644 index 000000000000..e3e13ed33a7e --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/ConnectionsSample.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.Connection; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; + +public class ConnectionsSample { + + private static ConnectionsClient connectionsClient + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildConnectionsClient(); + + public static void main(String[] args) { + + //listConnections(); + //getConnectionWithoutCredentials(); + //getConnectionWithCredentials(); + } + + public static void listConnections() { + // BEGIN:com.azure.ai.projects.ConnectionsSample.listConnections + + PagedIterable connections = connectionsClient.listConnections(); + for (Connection connection : connections) { + System.out.printf("Connection name: %s%n", connection.getName()); + } + + // END:com.azure.ai.projects.ConnectionsSample.listConnections + } + + public static void getConnectionWithoutCredentials() { + // BEGIN:com.azure.ai.projects.ConnectionsSample.getConnectionWithoutCredentials + + String connectionName = Configuration.getGlobalConfiguration().get("TEST_CONNECTION_NAME", ""); + Connection connection = connectionsClient.getConnection(connectionName, false); + + System.out.printf("Connection name: %s%n", connection.getName()); + + // END:com.azure.ai.projects.ConnectionsSample.getConnectionWithoutCredentials + } + + public static void getConnectionWithCredentials() { + // BEGIN:com.azure.ai.projects.ConnectionsSample.getConnectionWithCredentials + + String connectionName = Configuration.getGlobalConfiguration().get("TEST_CONNECTION_NAME", ""); + Connection connection = connectionsClient.getConnection(connectionName, true); + + System.out.printf("Connection name: %s%n", connection.getName()); + System.out.printf("Connection credentials: %s%n", connection.getCredentials().getType()); + + // END:com.azure.ai.projects.ConnectionsSample.getConnectionWithCredentials + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DatasetsAsyncSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DatasetsAsyncSample.java new file mode 100644 index 000000000000..9194b03b1812 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DatasetsAsyncSample.java @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.DatasetVersion; +import com.azure.ai.projects.models.FileDatasetVersion; +import com.azure.ai.projects.models.PendingUploadRequest; +import com.azure.ai.projects.models.PendingUploadResponse; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; + +public class DatasetsAsyncSample { + + private static DatasetsAsyncClient datasetsAsyncClient + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildDatasetsAsyncClient(); + + public static void main(String[] args) throws IOException, URISyntaxException { + // Using block() to wait for the async operations to complete in the sample + //createDatasetWithFile().block(); + listDatasets().blockLast(); + //listDatasetVersions().blockLast(); + //getDataset().block(); + //pendingUploadSample().block(); + //deleteDataset().block(); + //createOrUpdateDataset().block(); + } + + public static Mono createDatasetWithFile() throws IOException, URISyntaxException { + // BEGIN:com.azure.ai.projects.DatasetsAsyncSample.createDatasetWithFile + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersionString = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + Path filePath = getPath("product_info.md"); + + return datasetsAsyncClient.createDatasetWithFile(datasetName, datasetVersionString, filePath) + .doOnNext(createdDatasetVersion -> + System.out.println("Created dataset version: " + createdDatasetVersion.getId())); + + // END:com.azure.ai.projects.DatasetsAsyncSample.createDatasetWithFile + } + + public static Flux listDatasets() { + // BEGIN:com.azure.ai.projects.DatasetsAsyncSample.listDatasets + + System.out.println("Listing all datasets (latest versions):"); + return datasetsAsyncClient.listLatestDatasetVersions() + .doOnNext(dataset -> { + System.out.println("\nDataset name: " + dataset.getName()); + System.out.println("Dataset Id: " + dataset.getId()); + System.out.println("Dataset version: " + dataset.getVersion()); + System.out.println("Dataset type: " + dataset.getType()); + if (dataset.getDescription() != null) { + System.out.println("Description: " + dataset.getDescription()); + } + }); + + // END:com.azure.ai.projects.DatasetsAsyncSample.listDatasets + } + + public static Flux listDatasetVersions() { + // BEGIN:com.azure.ai.projects.DatasetsAsyncSample.listDatasetVersions + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "test"); + + System.out.println("Listing all versions of dataset: " + datasetName); + return datasetsAsyncClient.listDatasetVersions(datasetName) + .doOnNext(version -> { + System.out.println("\nDataset name: " + version.getName()); + System.out.println("Dataset version: " + version.getVersion()); + System.out.println("Dataset type: " + version.getType()); + if (version.getDataUri() != null) { + System.out.println("Data URI: " + version.getDataUri()); + } + }); + + // END:com.azure.ai.projects.DatasetsAsyncSample.listDatasetVersions + } + + public static Mono getDataset() { + // BEGIN:com.azure.ai.projects.DatasetsAsyncSample.getDataset + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "test"); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1"); + + return datasetsAsyncClient.getDatasetVersion(datasetName, datasetVersion) + .doOnNext(dataset -> { + System.out.println("Retrieved dataset:"); + System.out.println("Name: " + dataset.getName()); + System.out.println("Version: " + dataset.getVersion()); + System.out.println("Type: " + dataset.getType()); + if (dataset.getDataUri() != null) { + System.out.println("Data URI: " + dataset.getDataUri()); + } + if (dataset.getDescription() != null) { + System.out.println("Description: " + dataset.getDescription()); + } + }); + + // END:com.azure.ai.projects.DatasetsAsyncSample.getDataset + } + + public static Mono deleteDataset() { + // BEGIN:com.azure.ai.projects.DatasetsAsyncSample.deleteDataset + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + // Delete the specific version of the dataset + return datasetsAsyncClient.deleteDatasetVersion(datasetName, datasetVersion) + .doOnSuccess(unused -> + System.out.println("Deleted dataset: " + datasetName + ", version: " + datasetVersion)); + + // END:com.azure.ai.projects.DatasetsAsyncSample.deleteDataset + } + + public static Mono createOrUpdateDataset() { + // BEGIN:com.azure.ai.projects.DatasetsAsyncSample.createOrUpdateDataset + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + String dataUri = Configuration.getGlobalConfiguration().get("DATA_URI", "https://example.com/data.txt"); + + // Create a new FileDatasetVersion with provided dataUri + FileDatasetVersion fileDataset = new FileDatasetVersion() + .setDataUri(dataUri) + .setDescription("Sample dataset created via SDK"); + + // Create or update the dataset + return datasetsAsyncClient.createOrUpdateDatasetVersion( + datasetName, + datasetVersion, + fileDataset + ).doOnNext(createdDataset -> { + FileDatasetVersion fileDatasetVersion = (FileDatasetVersion) createdDataset; + System.out.println("Created/Updated dataset:"); + System.out.println("Name: " + fileDatasetVersion.getName()); + System.out.println("Version: " + fileDatasetVersion.getVersion()); + System.out.println("Data URI: " + fileDatasetVersion.getDataUri()); + }); + + // END:com.azure.ai.projects.DatasetsAsyncSample.createOrUpdateDataset + } + + public static Mono pendingUploadSample() { + // BEGIN:com.azure.ai.projects.DatasetsAsyncSample.pendingUploadSample + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + // Create a pending upload request for the dataset + PendingUploadRequest request = new PendingUploadRequest(); + + // Get the pending upload response with blob reference + return datasetsAsyncClient.pendingUpload(datasetName, datasetVersion, request) + .doOnNext(response -> { + System.out.println("Pending upload initiated with ID: " + response.getPendingUploadId()); + System.out.println("Blob URI: " + response.getBlobReference().getBlobUri()); + }); + + // END:com.azure.ai.projects.DatasetsAsyncSample.pendingUploadSample + } + + public static Path getPath(String fileName) throws FileNotFoundException, URISyntaxException { + URL resource = DatasetsAsyncSample.class.getClassLoader().getResource(fileName); + if (resource == null) { + throw new FileNotFoundException("File not found"); + } + + File file = new File(resource.toURI()); + return file.toPath(); + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DatasetsSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DatasetsSample.java new file mode 100644 index 000000000000..713dc47a537a --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DatasetsSample.java @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.DatasetVersion; +import com.azure.ai.projects.models.FileDatasetVersion; +import com.azure.ai.projects.models.PendingUploadRequest; +import com.azure.ai.projects.models.PendingUploadResponse; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; + +public class DatasetsSample { + + private static DatasetsClient datasetsClient + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildDatasetsClient(); + + public static void main(String[] args) throws IOException, URISyntaxException { + + //createDatasetWithFile(); + listDatasets(); + //listDatasetVersions(); + //getDataset(); + //pendingUploadSample(); + + //deleteDataset(); + //createOrUpdateDataset(); + } + + public static void createDatasetWithFile() throws IOException, URISyntaxException { + // BEGIN:com.azure.ai.projects.DatasetsSample.createDatasetWithFile + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersionString = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + Path filePath = getPath("product_info.md"); + + FileDatasetVersion createdDatasetVersion = datasetsClient.createDatasetWithFile(datasetName, datasetVersionString, filePath); + + System.out.println("Created dataset version: " + createdDatasetVersion.getId()); + + // END:com.azure.ai.projects.DatasetsSample.createDatasetWithFile + } + + public static void listDatasets() { + // BEGIN:com.azure.ai.projects.DatasetsSample.listDatasets + + System.out.println("Listing all datasets (latest versions):"); + datasetsClient.listLatestDatasetVersions().forEach(dataset -> { + System.out.println("\nDataset name: " + dataset.getName()); + System.out.println("Dataset Id: " + dataset.getId()); + System.out.println("Dataset version: " + dataset.getVersion()); + System.out.println("Dataset type: " + dataset.getType()); + if (dataset.getDescription() != null) { + System.out.println("Description: " + dataset.getDescription()); + } + }); + + // END:com.azure.ai.projects.DatasetsSample.listDatasets + } + + public static void listDatasetVersions() { + // BEGIN:com.azure.ai.projects.DatasetsSample.listDatasetVersions + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "test"); + + System.out.println("Listing all versions of dataset: " + datasetName); + datasetsClient.listDatasetVersions(datasetName).forEach(version -> { + System.out.println("\nDataset name: " + version.getName()); + System.out.println("Dataset version: " + version.getVersion()); + System.out.println("Dataset type: " + version.getType()); + if (version.getDataUri() != null) { + System.out.println("Data URI: " + version.getDataUri()); + } + }); + + // END:com.azure.ai.projects.DatasetsSample.listDatasetVersions + } + + public static void getDataset() { + // BEGIN:com.azure.ai.projects.DatasetsSample.getDataset + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "test"); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1"); + + DatasetVersion dataset = datasetsClient.getDatasetVersion(datasetName, datasetVersion); + + System.out.println("Retrieved dataset:"); + System.out.println("Name: " + dataset.getName()); + System.out.println("Version: " + dataset.getVersion()); + System.out.println("Type: " + dataset.getType()); + if (dataset.getDataUri() != null) { + System.out.println("Data URI: " + dataset.getDataUri()); + } + if (dataset.getDescription() != null) { + System.out.println("Description: " + dataset.getDescription()); + } + + // END:com.azure.ai.projects.DatasetsSample.getDataset + } + + public static void deleteDataset() { + // BEGIN:com.azure.ai.projects.DatasetsSample.deleteDataset + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + // Delete the specific version of the dataset + datasetsClient.deleteDatasetVersion(datasetName, datasetVersion); + + System.out.println("Deleted dataset: " + datasetName + ", version: " + datasetVersion); + + // END:com.azure.ai.projects.DatasetsSample.deleteDataset + } + + public static void createOrUpdateDataset() { + // BEGIN:com.azure.ai.projects.DatasetsSample.createOrUpdateDataset + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + String dataUri = Configuration.getGlobalConfiguration().get("DATA_URI", "https://example.com/data.txt"); + + // Create a new FileDatasetVersion with provided dataUri + FileDatasetVersion fileDataset = new FileDatasetVersion() + .setDataUri(dataUri) + .setDescription("Sample dataset created via SDK"); + + // Create or update the dataset + FileDatasetVersion createdDataset = (FileDatasetVersion) datasetsClient.createOrUpdateDatasetVersion( + datasetName, + datasetVersion, + fileDataset + ); + + System.out.println("Created/Updated dataset:"); + System.out.println("Name: " + createdDataset.getName()); + System.out.println("Version: " + createdDataset.getVersion()); + System.out.println("Data URI: " + createdDataset.getDataUri()); + + // END:com.azure.ai.projects.DatasetsSample.createOrUpdateDataset + } + + public static void pendingUploadSample() throws URISyntaxException, IOException { + // BEGIN:com.azure.ai.projects.DatasetsSample.pendingUploadSample + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + // Create a pending upload request for the dataset + PendingUploadRequest request = new PendingUploadRequest(); + + // Get the pending upload response with blob reference + PendingUploadResponse response = datasetsClient.pendingUpload(datasetName, datasetVersion, request); + + System.out.println("Pending upload initiated with ID: " + response.getPendingUploadId()); + System.out.println("Blob URI: " + response.getBlobReference().getBlobUri()); + + // END:com.azure.ai.projects.DatasetsSample.pendingUploadSample + } + + public static Path getPath(String fileName) throws FileNotFoundException, URISyntaxException { + URL resource = DatasetsSample.class.getClassLoader().getResource(fileName); + if (resource == null) { + throw new FileNotFoundException("File not found"); + } + + File file = new File(resource.toURI()); + return file.toPath(); + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DeploymentsAsyncSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DeploymentsAsyncSample.java new file mode 100644 index 000000000000..9e5d5109a76e --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DeploymentsAsyncSample.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.Deployment; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class DeploymentsAsyncSample { + + private static DeploymentsAsyncClient deploymentsAsyncClient + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildDeploymentsAsyncClient(); + + public static void main(String[] args) { + // Using block() to wait for the async operations to complete in the sample + listDeployments().blockLast(); + getDeployment().block(); + } + + public static Flux listDeployments() { + // BEGIN:com.azure.ai.projects.DeploymentsAsyncSample.listDeployments + + return deploymentsAsyncClient.listDeployments() + .doOnNext(deployment -> System.out.printf("Deployment name: %s%n", deployment.getName())); + + // END:com.azure.ai.projects.DeploymentsAsyncSample.listDeployments + } + + public static Mono getDeployment() { + // BEGIN:com.azure.ai.projects.DeploymentsAsyncSample.getDeployment + + String deploymentName = Configuration.getGlobalConfiguration().get("DEPLOYMENT_NAME", ""); + return deploymentsAsyncClient.getDeployment(deploymentName) + .doOnNext(deployment -> { + System.out.printf("Deployment name: %s%n", deployment.getName()); + System.out.printf("Deployment type: %s%n", deployment.getType().getValue()); + }); + + // END:com.azure.ai.projects.DeploymentsAsyncSample.getDeployment + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DeploymentsSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DeploymentsSample.java new file mode 100644 index 000000000000..0cbd38a1af94 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/DeploymentsSample.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.Deployment; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; + +public class DeploymentsSample { + + private static DeploymentsClient deploymentsClient + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildDeploymentsClient(); + + public static void main(String[] args) { + + //listDeployments(); + //getDeployment(); + } + + public static void listDeployments() { + // BEGIN:com.azure.ai.projects.DeploymentsSample.listDeployments + + PagedIterable deployments = deploymentsClient.listDeployments(); + for (Deployment deployment : deployments) { + System.out.printf("Deployment name: %s%n", deployment.getName()); + } + + // END:com.azure.ai.projects.DeploymentsSample.listDeployments + } + + public static void getDeployment() { + // BEGIN:com.azure.ai.projects.DeploymentsSample.getDeployment + + String deploymentName = Configuration.getGlobalConfiguration().get("DEPLOYMENT_NAME", ""); + Deployment deployment = deploymentsClient.getDeployment(deploymentName); + + System.out.printf("Deployment name: %s%n", deployment.getName()); + System.out.printf("Deployment type: %s%n", deployment.getType().getValue()); + + // END:com.azure.ai.projects.DeploymentsSample.getDeployment + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/EvaluationsAsyncSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/EvaluationsAsyncSample.java new file mode 100644 index 000000000000..c81f9ab3a435 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/EvaluationsAsyncSample.java @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.Evaluation; +import com.azure.ai.projects.models.EvaluatorConfiguration; +import com.azure.ai.projects.models.EvaluatorId; +import com.azure.ai.projects.models.InputDataset; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import java.util.HashMap; +import java.util.Map; + +public class EvaluationsAsyncSample { + private static AIProjectClientBuilder clientBuilder + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()); + + private static EvaluationsAsyncClient evaluationsAsyncClient = clientBuilder.buildEvaluationsAsyncClient(); + private static DatasetsAsyncClient datasetsAsyncClient = clientBuilder.buildDatasetsAsyncClient(); + + public static void main(String[] args) { + // Using block() to wait for the async operations to complete in the sample + //createEvaluation().block(); + //getEvaluation().block(); + listEvaluations().blockLast(); + } + + public static Flux listEvaluations() { + // BEGIN:com.azure.ai.projects.EvaluationsAsyncSample.listEvaluations + + System.out.println("Listing all evaluations:"); + return evaluationsAsyncClient.listEvaluations() + .doOnNext(evaluation -> { + System.out.println("Display Name: " + evaluation.getDisplayName()); + System.out.println("Status: " + evaluation.getStatus()); + System.out.println("Data Type: " + evaluation.getData().getType()); + + if (evaluation.getDescription() != null) { + System.out.println("Description: " + evaluation.getDescription()); + } + + System.out.println("Evaluators:"); + evaluation.getEvaluators().forEach((name, evaluator) -> { + System.out.println(" - " + name + ": " + evaluator.getId()); + }); + }); + + // END:com.azure.ai.projects.EvaluationsAsyncSample.listEvaluations + } + + public static Mono getEvaluation() { + // BEGIN:com.azure.ai.projects.EvaluationsAsyncSample.getEvaluation + + String evaluationId = Configuration.getGlobalConfiguration().get("EVALUATION_ID", "my-evaluation-id"); + + return evaluationsAsyncClient.getEvaluation(evaluationId) + .doOnNext(evaluation -> { + System.out.println("Retrieved evaluation:"); + System.out.println("Display Name: " + evaluation.getDisplayName()); + System.out.println("Status: " + evaluation.getStatus()); + System.out.println("Data Type: " + evaluation.getData().getType()); + + if (evaluation.getDescription() != null) { + System.out.println("Description: " + evaluation.getDescription()); + } + + if (evaluation.getTags() != null) { + System.out.println("Tags:"); + evaluation.getTags().forEach((key, value) -> { + System.out.println(" " + key + ": " + value); + }); + } + + System.out.println("Evaluators:"); + evaluation.getEvaluators().forEach((name, evaluator) -> { + System.out.println(" - " + name + ": " + evaluator.getId()); + + if (evaluator.getDataMapping() != null) { + System.out.println(" Data Mapping:"); + evaluator.getDataMapping().forEach((k, v) -> { + System.out.println(" " + k + " -> " + v); + }); + } + }); + }); + + // END:com.azure.ai.projects.EvaluationsAsyncSample.getEvaluation + } + + public static Mono createEvaluation() { + // BEGIN:com.azure.ai.projects.EvaluationsAsyncSample.createEvaluation + + // Create an evaluation definition + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "test"); + String version = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1"); + + return datasetsAsyncClient.getDatasetVersion(datasetName, version) + .flatMap(datasetVersion -> { + InputDataset dataset = new InputDataset(datasetVersion.getId()); + Evaluation evaluation = new Evaluation( + dataset, + mapOf("relevance", + new EvaluatorConfiguration(EvaluatorId.RELEVANCE.getValue()) + .setInitParams(mapOf("deployment_name", BinaryData.fromObject("gpt-4o"))))) + .setDisplayName("Sample Evaluation") + .setDescription("This is a sample evaluation created using the SDK"); + + // Create the evaluation + return evaluationsAsyncClient.createEvaluation(evaluation); + }) + .doOnNext(createdEvaluation -> { + System.out.println("Created evaluation:"); + System.out.println("Display Name: " + createdEvaluation.getDisplayName()); + System.out.println("Status: " + createdEvaluation.getStatus()); + }); + + // END:com.azure.ai.projects.EvaluationsAsyncSample.createEvaluation + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/EvaluationsSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/EvaluationsSample.java new file mode 100644 index 000000000000..662ea6c6f1de --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/EvaluationsSample.java @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.DatasetVersion; +import com.azure.ai.projects.models.Evaluation; +import com.azure.ai.projects.models.EvaluatorConfiguration; +import com.azure.ai.projects.models.EvaluatorId; +import com.azure.ai.projects.models.InputDataset; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import java.util.HashMap; +import java.util.Map; + +public class EvaluationsSample { + private static AIProjectClientBuilder clientBuilder + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()); + + private static EvaluationsClient evaluationsClient = clientBuilder.buildEvaluationsClient(); + private static DatasetsClient datasetsClient = clientBuilder.buildDatasetsClient(); + + + public static void main(String[] args) { + + //createEvaluation(); + + //getEvaluation(); + //listEvaluations(); + } + + public static void listEvaluations() { + // BEGIN:com.azure.ai.projects.EvaluationsSample.listEvaluations + + System.out.println("Listing all evaluations:"); + evaluationsClient.listEvaluations().forEach(evaluation -> { + System.out.println("Display Name: " + evaluation.getDisplayName()); + System.out.println("Status: " + evaluation.getStatus()); + System.out.println("Data Type: " + evaluation.getData().getType()); + + if (evaluation.getDescription() != null) { + System.out.println("Description: " + evaluation.getDescription()); + } + + System.out.println("Evaluators:"); + evaluation.getEvaluators().forEach((name, evaluator) -> { + System.out.println(" - " + name + ": " + evaluator.getId()); + }); + }); + + // END:com.azure.ai.projects.EvaluationsSample.listEvaluations + } + + public static void getEvaluation() { + // BEGIN:com.azure.ai.projects.EvaluationsSample.getEvaluation + + String evaluationId = Configuration.getGlobalConfiguration().get("EVALUATION_ID", "my-evaluation-id"); + + Evaluation evaluation = evaluationsClient.getEvaluation(evaluationId); + + System.out.println("Retrieved evaluation:"); + System.out.println("Display Name: " + evaluation.getDisplayName()); + System.out.println("Status: " + evaluation.getStatus()); + System.out.println("Data Type: " + evaluation.getData().getType()); + + if (evaluation.getDescription() != null) { + System.out.println("Description: " + evaluation.getDescription()); + } + + if (evaluation.getTags() != null) { + System.out.println("Tags:"); + evaluation.getTags().forEach((key, value) -> { + System.out.println(" " + key + ": " + value); + }); + } + + System.out.println("Evaluators:"); + evaluation.getEvaluators().forEach((name, evaluator) -> { + System.out.println(" - " + name + ": " + evaluator.getId()); + + if (evaluator.getDataMapping() != null) { + System.out.println(" Data Mapping:"); + evaluator.getDataMapping().forEach((k, v) -> { + System.out.println(" " + k + " -> " + v); + }); + } + }); + + // END:com.azure.ai.projects.EvaluationsSample.getEvaluation + } + + public static void createEvaluation() { + // BEGIN:com.azure.ai.projects.EvaluationsSample.createEvaluation + + // Create an evaluation definition + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "test"); + String version = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1"); + DatasetVersion datasetVersion = datasetsClient.getDatasetVersion(datasetName, version); + + InputDataset dataset = new InputDataset(datasetVersion.getId()); + Evaluation evaluation = new Evaluation( + dataset, + mapOf("relevance", + new EvaluatorConfiguration(EvaluatorId.RELEVANCE.getValue()) + .setInitParams(mapOf("deployment_name", BinaryData.fromObject("gpt-4o"))))) + .setDisplayName("Sample Evaluation") + .setDescription("This is a sample evaluation created using the SDK"); + + // Create the evaluation + Evaluation createdEvaluation = evaluationsClient.createEvaluation(evaluation); + + System.out.println("Created evaluation:"); + System.out.println("Display Name: " + createdEvaluation.getDisplayName()); + System.out.println("Status: " + createdEvaluation.getStatus()); + + // END:com.azure.ai.projects.EvaluationsSample.createEvaluation + } + + // Use "Map.of" if available + @SuppressWarnings("unchecked") + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/IndexesAsyncSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/IndexesAsyncSample.java new file mode 100644 index 000000000000..bc52c1fd8d35 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/IndexesAsyncSample.java @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.AzureAISearchIndex; +import com.azure.ai.projects.models.Index; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class IndexesAsyncSample { + + private static IndexesAsyncClient indexesAsyncClient + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildIndexesAsyncClient(); + + public static void main(String[] args) { + // Using block() to wait for the async operations to complete in the sample + //createOrUpdateIndex().block(); + //listIndexVersions().blockLast(); + //getIndex().block(); + //deleteIndex().block(); + listIndexes().blockLast(); + } + + public static Mono createOrUpdateIndex() { + // BEGIN:com.azure.ai.projects.IndexesAsyncSample.createOrUpdateIndex + + String indexName = Configuration.getGlobalConfiguration().get("INDEX_NAME", "my-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("INDEX_VERSION", "2.0"); + String aiSearchConnectionName = Configuration.getGlobalConfiguration().get("AI_SEARCH_CONNECTION_NAME", ""); + String aiSearchIndexName = Configuration.getGlobalConfiguration().get("AI_SEARCH_INDEX_NAME", ""); + + return indexesAsyncClient.createOrUpdateIndexVersion( + indexName, + indexVersion, + new AzureAISearchIndex() + .setConnectionName(aiSearchConnectionName) + .setIndexName(aiSearchIndexName) + ).doOnNext(index -> System.out.println("Index created: " + index.getName())); + + // END:com.azure.ai.projects.IndexesAsyncSample.createOrUpdateIndex + } + + public static Flux listIndexes() { + // BEGIN:com.azure.ai.projects.IndexesAsyncSample.listIndexes + + return indexesAsyncClient.listLatestIndexVersions() + .doOnNext(index -> { + System.out.println("Index name: " + index.getName()); + System.out.println("Index version: " + index.getVersion()); + }); + + // END:com.azure.ai.projects.IndexesAsyncSample.listIndexes + } + + public static Flux listIndexVersions() { + // BEGIN:com.azure.ai.projects.IndexesAsyncSample.listIndexVersions + + String indexName = Configuration.getGlobalConfiguration().get("INDEX_NAME", "my-index"); + + return indexesAsyncClient.listIndexVersions(indexName) + .doOnNext(index -> { + System.out.println("Index name: " + index.getName()); + System.out.println("Index version: " + index.getVersion()); + System.out.println("Index type: " + index.getType()); + }); + + // END:com.azure.ai.projects.IndexesAsyncSample.listIndexVersions + } + + public static Mono getIndex() { + // BEGIN:com.azure.ai.projects.IndexesAsyncSample.getIndex + + String indexName = Configuration.getGlobalConfiguration().get("INDEX_NAME", "my-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("INDEX_VERSION", "1.0"); + + return indexesAsyncClient.getIndexVersion(indexName, indexVersion) + .doOnNext(index -> { + System.out.println("Retrieved index:"); + System.out.println("Name: " + index.getName()); + System.out.println("Version: " + index.getVersion()); + System.out.println("Type: " + index.getType()); + }); + + // END:com.azure.ai.projects.IndexesAsyncSample.getIndex + } + + public static Mono deleteIndex() { + // BEGIN:com.azure.ai.projects.IndexesAsyncSample.deleteIndex + + String indexName = Configuration.getGlobalConfiguration().get("INDEX_NAME", "my-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("INDEX_VERSION", "1.0"); + + // Delete the index version + return indexesAsyncClient.deleteIndexVersion(indexName, indexVersion) + .doOnSuccess(unused -> + System.out.println("Deleted index: " + indexName + ", version: " + indexVersion)); + + // END:com.azure.ai.projects.IndexesAsyncSample.deleteIndex + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/IndexesSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/IndexesSample.java new file mode 100644 index 000000000000..cd9cb4d02b4e --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/IndexesSample.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.AzureAISearchIndex; +import com.azure.ai.projects.models.Index; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; + +public class IndexesSample { + + private static IndexesClient indexesClient + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildIndexesClient(); + + public static void main(String[] args) { + // Uncomment the sample you want to run + //createOrUpdateIndex(); + //listIndexVersions(); + //getIndex(); + //deleteIndex(); + //listIndexes(); + } + + public static void createOrUpdateIndex() { + // BEGIN:com.azure.ai.projects.IndexesGetSample.createOrUpdateIndex + + String indexName = Configuration.getGlobalConfiguration().get("INDEX_NAME", "my-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("INDEX_VERSION", "2.0"); + String aiSearchConnectionName = Configuration.getGlobalConfiguration().get("AI_SEARCH_CONNECTION_NAME", ""); + String aiSearchIndexName = Configuration.getGlobalConfiguration().get("AI_SEARCH_INDEX_NAME", ""); + + Index index = indexesClient.createOrUpdateIndexVersion( + indexName, + indexVersion, + new AzureAISearchIndex() + .setConnectionName(aiSearchConnectionName) + .setIndexName(aiSearchIndexName) + ); + + System.out.println("Index created: " + index.getName()); + + // END:com.azure.ai.projects.IndexesGetSample.createOrUpdateIndex + } + + public static void listIndexes() { + // BEGIN:com.azure.ai.projects.IndexesListSample.listIndexes + + indexesClient.listLatestIndexVersions().forEach(index -> { + System.out.println("Index name: " + index.getName()); + System.out.println("Index version: " + index.getVersion()); + }); + + // END:com.azure.ai.projects.IndexesListSample.listIndexes + } + + public static void listIndexVersions() { + // BEGIN:com.azure.ai.projects.IndexesListVersionsSample.listIndexVersions + + String indexName = Configuration.getGlobalConfiguration().get("INDEX_NAME", "my-index"); + + indexesClient.listIndexVersions(indexName).forEach(index -> { + System.out.println("Index name: " + index.getName()); + System.out.println("Index version: " + index.getVersion()); + System.out.println("Index type: " + index.getType()); + }); + + // END:com.azure.ai.projects.IndexesListVersionsSample.listIndexVersions + } + + public static void getIndex() { + // BEGIN:com.azure.ai.projects.IndexesGetSample.getIndex + + String indexName = Configuration.getGlobalConfiguration().get("INDEX_NAME", "my-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("INDEX_VERSION", "1.0"); + + Index index = indexesClient.getIndexVersion(indexName, indexVersion); + + System.out.println("Retrieved index:"); + System.out.println("Name: " + index.getName()); + System.out.println("Version: " + index.getVersion()); + System.out.println("Type: " + index.getType()); + + // END:com.azure.ai.projects.IndexesGetSample.getIndex + } + + public static void deleteIndex() { + // BEGIN:com.azure.ai.projects.IndexesDeleteSample.deleteIndex + + String indexName = "test-index"; //Configuration.getGlobalConfiguration().get("INDEX_NAME", "my-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("INDEX_VERSION", "1.0"); + + // Delete the index version + indexesClient.deleteIndexVersion(indexName, indexVersion); + + System.out.println("Deleted index: " + indexName + ", version: " + indexVersion); + + // END:com.azure.ai.projects.IndexesDeleteSample.deleteIndex + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/InferenceAsyncSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/InferenceAsyncSample.java new file mode 100644 index 000000000000..0cf4027bc003 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/InferenceAsyncSample.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.inference.ChatCompletionsAsyncClient; +import com.azure.ai.inference.ChatCompletionsClientBuilder; +import com.azure.ai.inference.EmbeddingsAsyncClient; +import com.azure.ai.inference.EmbeddingsClientBuilder; +import com.azure.ai.inference.ImageEmbeddingsAsyncClient; +import com.azure.ai.inference.ImageEmbeddingsClientBuilder; +import com.azure.ai.inference.models.ChatCompletionsOptions; +import com.azure.ai.inference.models.ChatRequestUserMessage; +import com.azure.ai.inference.models.EmbeddingItem; +import com.azure.ai.inference.models.ImageEmbeddingInput; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import reactor.core.publisher.Mono; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class InferenceAsyncSample { + + private static ChatCompletionsAsyncClient chatCompletionsAsyncClient + = new ChatCompletionsClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + private static ImageEmbeddingsAsyncClient imageEmbeddingsAsyncClient + = new ImageEmbeddingsClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + private static EmbeddingsAsyncClient embeddingsAsyncClient + = new EmbeddingsClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + + public static void main(String[] args) { + + } + + public static Mono embeddingsClientSample() { + // BEGIN: com.azure.ai.projects.InferenceAsyncSample.embeddingsClientSample + + List promptList = new ArrayList<>(); + String prompt = "Tell me 3 jokes about trains"; + promptList.add(prompt); + + return embeddingsAsyncClient.embed(promptList) + .flatMap(embeddings -> { + for (EmbeddingItem item : embeddings.getData()) { + System.out.printf("Index: %d.%n", item.getIndex()); + for (Float embedding : item.getEmbeddingList()) { + System.out.printf("%f;", embedding); + } + System.out.println(); + } + return Mono.empty(); + }); + + // END: com.azure.ai.projects.InferenceAsyncSample.embeddingsClientSample + } + + public static Mono chatCompletionsClientSample() { + // BEGIN: com.azure.ai.projects.InferenceAsyncSample.chatCompletionsClientSample + + ChatCompletionsOptions options = new ChatCompletionsOptions(Arrays.asList( + new ChatRequestUserMessage("How many feet are in a mile?") + )); + + return chatCompletionsAsyncClient.complete(options) + .flatMap(chatCompletions -> { + System.out.println(chatCompletions.getChoice().getMessage().getContent()); + return Mono.empty(); + }); + + // END: com.azure.ai.projects.InferenceAsyncSample.chatCompletionsClientSample + } + + public static Mono imageEmbeddingsClientSample(String imageUrl) { + // BEGIN: com.azure.ai.projects.InferenceAsyncSample.imageEmbeddingsClientSample + + return Mono.fromCallable(() -> SampleUtils.getPath(imageUrl)) + .flatMap(imagePath -> + imageEmbeddingsAsyncClient.embed(Arrays.asList(new ImageEmbeddingInput(imagePath, "png"))) + ) + .flatMap(embeddings -> { + for (EmbeddingItem item : embeddings.getData()) { + System.out.printf("Index: %d.%n", item.getIndex()); + for (Float embedding : item.getEmbeddingList()) { + System.out.printf("%f;", embedding); + } + System.out.println(); + } + return Mono.empty(); + }); + + // END: com.azure.ai.projects.InferenceAsyncSample.imageEmbeddingsClientSample + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/InferenceSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/InferenceSample.java new file mode 100644 index 000000000000..226c2fb8eb35 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/InferenceSample.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.inference.ChatCompletionsClient; +import com.azure.ai.inference.ChatCompletionsClientBuilder; +import com.azure.ai.inference.EmbeddingsClient; +import com.azure.ai.inference.EmbeddingsClientBuilder; +import com.azure.ai.inference.ImageEmbeddingsClient; +import com.azure.ai.inference.ImageEmbeddingsClientBuilder; +import com.azure.ai.inference.models.ChatCompletions; +import com.azure.ai.inference.models.ChatCompletionsOptions; +import com.azure.ai.inference.models.ChatRequestUserMessage; +import com.azure.ai.inference.models.EmbeddingItem; +import com.azure.ai.inference.models.EmbeddingsResult; +import com.azure.ai.inference.models.ImageEmbeddingInput; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import java.io.FileNotFoundException; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class InferenceSample { + + private static ChatCompletionsClient chatCompletionsClient + = new ChatCompletionsClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + private static ImageEmbeddingsClient imageEmbeddingsClient + = new ImageEmbeddingsClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + private static EmbeddingsClient embeddingsClient + = new EmbeddingsClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + + public static void main(String[] args) { + embeddingsClientSample(); + } + + public static void embeddingsClientSample() { + // BEGIN: com.azure.ai.projects.InferenceSample.embeddingsClientSample + + List promptList = new ArrayList<>(); + String prompt = "Tell me 3 jokes about trains"; + promptList.add(prompt); + + EmbeddingsResult embeddings = embeddingsClient.embed(promptList); + + for (EmbeddingItem item : embeddings.getData()) { + System.out.printf("Index: %d.%n", item.getIndex()); + for (Float embedding : item.getEmbeddingList()) { + System.out.printf("%f;", embedding); + } + } + + // END: com.azure.ai.projects.InferenceSample.embeddingsClientSample + } + + public static void chatCompletionsClientSample() { + // BEGIN: com.azure.ai.projects.InferenceSample.chatCompletionsClientSample + + ChatCompletionsOptions options = new ChatCompletionsOptions(Arrays.asList( + new ChatRequestUserMessage("How many feet are in a mile?") + )); + + ChatCompletions chatCompletions = chatCompletionsClient.complete(options); + System.out.println(chatCompletions.getChoice().getMessage().getContent()); + + // END: com.azure.ai.projects.InferenceSample.chatCompletionsClientSample + } + + public static void imageEmbeddingsClientSample() throws FileNotFoundException, URISyntaxException { + // BEGIN: com.azure.ai.projects.InferenceSample.imageEmbeddingsClientSample + + String imageUrl = "sample.png"; + Path imagePath = SampleUtils.getPath(imageUrl); + + EmbeddingsResult embeddings = imageEmbeddingsClient + .embed(Arrays.asList(new ImageEmbeddingInput(imagePath, "png"))); + + for (EmbeddingItem item : embeddings.getData()) { + System.out.printf("Index: %d.%n", item.getIndex()); + for (Float embedding : item.getEmbeddingList()) { + System.out.printf("%f;", embedding); + } + } + + // END: com.azure.ai.projects.InferenceSample.imageEmbeddingsClientSample + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/ReadmeSamples.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/ReadmeSamples.java new file mode 100644 index 000000000000..52d1b33e83df --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/ReadmeSamples.java @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) TypeSpec Code Generator. + +package com.azure.ai.projects; + +public final class ReadmeSamples { + public void readmeSamples() { + // BEGIN: com.azure.ai.projects.readme + // END: com.azure.ai.projects.readme + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/SampleUtils.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/SampleUtils.java new file mode 100644 index 000000000000..cb316f31da3f --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/SampleUtils.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import java.io.File; +import java.io.FileNotFoundException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; + +public class SampleUtils { + + public static Path getPath(String fileName) throws FileNotFoundException, URISyntaxException { + URL resource = SampleUtils.class.getClassLoader().getResource(fileName); + if (resource == null) { + throw new FileNotFoundException("File not found"); + } + + File file = new File(resource.toURI()); + return file.toPath(); + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/TelemetryAsyncSample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/TelemetryAsyncSample.java new file mode 100644 index 000000000000..a4fc9a02e57b --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/TelemetryAsyncSample.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import reactor.core.publisher.Mono; +import java.time.Duration; + +public class TelemetryAsyncSample { + + private static TelemetryAsyncClient telemetryAsyncClient + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildTelemetryAsyncClient(); + + public static void main(String[] args) { + + getConnectionString() + .block(Duration.ofMinutes(1)); + } + + public static Mono getConnectionString() { + // BEGIN:com.azure.ai.projects.TelemetryAsyncSample.getConnectionString + + return telemetryAsyncClient.getConnectionString() + .doOnNext(connectionString -> + System.out.println("Connection string (async): " + connectionString)) + .doOnError(error -> + System.err.println("Error retrieving connection string: " + error.getMessage())) + .then(); + + // END:com.azure.ai.projects.TelemetryAsyncSample.getConnectionString + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/TelemetrySample.java b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/TelemetrySample.java new file mode 100644 index 000000000000..cae00926f3da --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/java/com/azure/ai/projects/TelemetrySample.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; + +public class TelemetrySample { + + private static TelemetryClient telemetryClient + = new AIProjectClientBuilder().endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT", "endpoint")) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildTelemetryClient(); + + public static void main(String[] args) { + getConnectionString(); + } + + public static void getConnectionString() { + // BEGIN:com.azure.ai.projects.TelemetrySample.getConnectionString + + String connectionString = telemetryClient.getConnectionString(); + System.out.println("Connection string: " + connectionString); + + // END:com.azure.ai.projects.TelemetrySample.getConnectionString + } +} diff --git a/sdk/ai/azure-ai-projects/src/samples/resources/product_info.md b/sdk/ai/azure-ai-projects/src/samples/resources/product_info.md new file mode 100644 index 000000000000..041155831d53 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/samples/resources/product_info.md @@ -0,0 +1,51 @@ +# Information about product item_number: 1 + +## Brand +Contoso Galaxy Innovations + +## Category +Smart Eyewear + +## Features +- Augmented Reality interface +- Voice-controlled AI assistant +- HD video recording with 3D audio +- UV protection and blue light filtering +- Wireless charging with extended battery life + +## User Guide + +### 1. Introduction +Introduction to your new SmartView Glasses + +### 2. Product Overview +Overview of features and controls + +### 3. Sizing and Fit +Finding your perfect fit and style adjustments + +### 4. Proper Care and Maintenance +Cleaning and caring for your SmartView Glasses + +### 5. Break-in Period +Adjusting to the augmented reality experience + +### 6. Safety Tips +Safety guidelines for public and private spaces + +### 7. Troubleshooting +Quick fixes for common issues + +## Warranty Information +Two-year limited warranty on all electronic components + +## Contact Information +Customer Support at support@contoso-galaxy-innovations.com + +## Return Policy +30-day return policy with no questions asked + +## FAQ +- How to sync your SmartView Glasses with your devices +- Troubleshooting connection issues +- Customizing your augmented reality environment diff --git a/sdk/ai/azure-ai-projects/src/samples/resources/sample.png b/sdk/ai/azure-ai-projects/src/samples/resources/sample.png new file mode 100644 index 000000000000..55dafd287ef7 Binary files /dev/null and b/sdk/ai/azure-ai-projects/src/samples/resources/sample.png differ diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/ClientTestBase.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/ClientTestBase.java new file mode 100644 index 000000000000..f01fcb97af5b --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/ClientTestBase.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.core.http.HttpClient; +import com.azure.core.test.TestMode; +import com.azure.core.test.TestProxyTestBase; +import com.azure.core.test.models.CustomMatcher; +import com.azure.core.test.models.TestProxySanitizer; +import com.azure.core.test.models.TestProxySanitizerType; +import com.azure.core.test.utils.MockTokenCredential; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import java.io.File; +import java.io.FileNotFoundException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; + +public class ClientTestBase extends TestProxyTestBase { + + private boolean sanitizersRemoved = false; + + protected AIProjectClientBuilder getClientBuilder(HttpClient httpClient) { + + AIProjectClientBuilder builder = new AIProjectClientBuilder() + .httpClient(interceptorManager.isPlaybackMode() ? interceptorManager.getPlaybackClient() : httpClient); + TestMode testMode = getTestMode(); + if (testMode != TestMode.LIVE) { + addCustomMatchers(); + addTestRecordCustomSanitizers(); + if (!sanitizersRemoved) { + interceptorManager.removeSanitizers("AZSDK3430", "AZSDK3493", "AZSDK2015"); + sanitizersRemoved = true; + } + } + + if (testMode == TestMode.PLAYBACK) { + builder.endpoint("https://localhost:8080").credential(new MockTokenCredential()); + } else if (testMode == TestMode.RECORD) { + builder.addPolicy(interceptorManager.getRecordPolicy()) + .endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT")) + .credential(new DefaultAzureCredentialBuilder().build()); + } else { + builder.endpoint(Configuration.getGlobalConfiguration().get("ENDPOINT")) + .credential(new DefaultAzureCredentialBuilder().build()); + } + + String version = Configuration.getGlobalConfiguration().get("SERVICE_VERSION"); + ProjectsServiceVersion serviceVersion + = version != null ? ProjectsServiceVersion.valueOf(version) : ProjectsServiceVersion.V2025_05_15_PREVIEW; + builder.serviceVersion(serviceVersion); + return builder; + } + + private void addTestRecordCustomSanitizers() { + + ArrayList sanitizers = new ArrayList<>(); + sanitizers.add(new TestProxySanitizer("$..key", null, "REDACTED", TestProxySanitizerType.BODY_KEY)); + sanitizers.add(new TestProxySanitizer("$..endpoint", "https://.+?/api/projects/.+?/", "https://REDACTED/", + TestProxySanitizerType.URL)); + sanitizers.add(new TestProxySanitizer("Content-Type", + "(^multipart\\/form-data; boundary=[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{2})", + "multipart\\/form-data; boundary=BOUNDARY", TestProxySanitizerType.HEADER)); + + interceptorManager.addSanitizers(sanitizers); + + } + + private void addCustomMatchers() { + interceptorManager.addMatchers(new CustomMatcher().setExcludedHeaders(Arrays.asList("Cookie", "Set-Cookie"))); + } + + protected Path getPath(String fileName) throws FileNotFoundException, URISyntaxException { + URL resource = ClientTestBase.class.getClassLoader().getResource(fileName); + if (resource == null) { + throw new FileNotFoundException("File not found"); + } + + File file = new File(resource.toURI()); + return file.toPath(); + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/ConnectionsAsyncClientTest.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/ConnectionsAsyncClientTest.java new file mode 100644 index 000000000000..036f354cb82e --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/ConnectionsAsyncClientTest.java @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.Connection; +import com.azure.ai.projects.models.ConnectionType; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import static com.azure.ai.projects.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class ConnectionsAsyncClientTest extends ClientTestBase { + + private AIProjectClientBuilder clientBuilder; + private ConnectionsAsyncClient connectionsAsyncClient; + + private void setup(HttpClient httpClient) { + clientBuilder = getClientBuilder(httpClient); + connectionsAsyncClient = clientBuilder.buildConnectionsAsyncClient(); + } + + /** + * Helper method to verify a Connection has valid properties. + * @param connection The connection to validate + * @param expectedName The expected name of the connection, or null if no specific name is expected + * @param expectedType The expected connection type, or null if no specific type is expected + * @param shouldBeDefault Whether the connection should be a default connection, or null if not checking this property + */ + private void assertValidConnection(Connection connection, String expectedName, ConnectionType expectedType, + Boolean shouldBeDefault) { + Assertions.assertNotNull(connection); + Assertions.assertNotNull(connection.getName()); + Assertions.assertNotNull(connection.getId()); + Assertions.assertNotNull(connection.getType()); + Assertions.assertNotNull(connection.getTarget()); + Assertions.assertNotNull(connection.getCredentials()); + + if (expectedName != null) { + Assertions.assertEquals(expectedName, connection.getName()); + } + + if (expectedType != null) { + Assertions.assertEquals(expectedType, connection.getType()); + } + + if (shouldBeDefault != null) { + Assertions.assertEquals(shouldBeDefault, connection.isDefault()); + } + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListConnectionsAsync(HttpClient httpClient) { + setup(httpClient); + + // Verify that listing connections returns results + PagedFlux connectionsFlux = connectionsAsyncClient.listConnections(); + Assertions.assertNotNull(connectionsFlux); + + // Collect all connections and verify + List connections = new ArrayList<>(); + connectionsFlux.collectList().block(Duration.ofSeconds(30)); + + System.out.println("Connection list retrieved successfully" + + (connections.size() > 0 ? " with " + connections.size() + " connections" : " (empty list)")); + + // Verify the first connection if available + StepVerifier.create(connectionsFlux.take(1)) + .assertNext(connection -> assertValidConnection(connection, null, null, null)) + .verifyComplete(); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListConnectionsWithFiltersAsync(HttpClient httpClient) { + setup(httpClient); + + // Test listing connections with type filter + PagedFlux azureOpenAIConnections + = connectionsAsyncClient.listConnections(ConnectionType.AZURE_OPEN_AI, null); + Assertions.assertNotNull(azureOpenAIConnections); + + // Verify that all returned connections have the correct type + StepVerifier.create(azureOpenAIConnections.take(10)).thenConsumeWhile(connection -> { + assertValidConnection(connection, null, ConnectionType.AZURE_OPEN_AI, null); + return true; + }).verifyComplete(); + + // Test listing default connections + PagedFlux defaultConnections = connectionsAsyncClient.listConnections(null, true); + Assertions.assertNotNull(defaultConnections); + + // Verify that all returned connections are default connections + StepVerifier.create(defaultConnections.take(10)).thenConsumeWhile(connection -> { + assertValidConnection(connection, null, null, true); + return true; + }).verifyComplete(); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetConnectionWithoutCredentialsAsync(HttpClient httpClient) { + setup(httpClient); + + String connectionName = Configuration.getGlobalConfiguration().get("TEST_CONNECTION_NAME", "agentaisearch2aqa"); + + Mono connectionMono = connectionsAsyncClient.getConnection(connectionName, false); + + try { + // Test retrieving a connection + StepVerifier.create(connectionMono).assertNext(connection -> { + assertValidConnection(connection, connectionName, null, null); + Assertions.assertNotNull(connection.getCredentials().getType()); + System.out.println("Connection retrieved successfully: " + connection.getName()); + }).verifyComplete(); + } catch (Exception e) { + // If the connection doesn't exist, this will throw an exception + // We'll handle this case by printing a message and passing the test + System.out.println("Connection not found: " + connectionName); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetConnectionWithCredentialsAsync(HttpClient httpClient) { + setup(httpClient); + + String connectionName = Configuration.getGlobalConfiguration().get("TEST_CONNECTION_NAME", "agentaisearch2aqa"); + + Mono connectionMono = connectionsAsyncClient.getConnectionWithCredentials(connectionName); + + try { + // Test retrieving a connection with credentials + StepVerifier.create(connectionMono).assertNext(connection -> { + assertValidConnection(connection, connectionName, null, null); + Assertions.assertNotNull(connection.getCredentials().getType()); + System.out.println("Connection with credentials retrieved successfully: " + connection.getName()); + System.out.println("Credential type: " + connection.getCredentials().getType()); + }).verifyComplete(); + } catch (Exception e) { + // If the connection doesn't exist, this will throw an exception + // We'll handle this case by printing a message and passing the test + System.out.println("Connection not found: " + connectionName); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/ConnectionsClientTest.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/ConnectionsClientTest.java new file mode 100644 index 000000000000..42f744391973 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/ConnectionsClientTest.java @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.Connection; +import com.azure.ai.projects.models.ConnectionType; +import com.azure.core.http.HttpClient; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static com.azure.ai.projects.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class ConnectionsClientTest extends ClientTestBase { + + private AIProjectClientBuilder clientBuilder; + private ConnectionsClient connectionsClient; + + private void setup(HttpClient httpClient) { + clientBuilder = getClientBuilder(httpClient); + connectionsClient = clientBuilder.buildConnectionsClient(); + } + + /** + * Helper method to verify a Connection has valid properties. + * @param connection The connection to validate + * @param expectedName The expected name of the connection, or null if no specific name is expected + * @param expectedType The expected connection type, or null if no specific type is expected + * @param shouldBeDefault Whether the connection should be a default connection, or null if not checking this property + */ + private void assertValidConnection(Connection connection, String expectedName, ConnectionType expectedType, + Boolean shouldBeDefault) { + Assertions.assertNotNull(connection); + Assertions.assertNotNull(connection.getName()); + Assertions.assertNotNull(connection.getId()); + Assertions.assertNotNull(connection.getType()); + Assertions.assertNotNull(connection.getTarget()); + Assertions.assertNotNull(connection.getCredentials()); + + if (expectedName != null) { + Assertions.assertEquals(expectedName, connection.getName()); + } + + if (expectedType != null) { + Assertions.assertEquals(expectedType, connection.getType()); + } + + if (shouldBeDefault != null) { + Assertions.assertEquals(shouldBeDefault, connection.isDefault()); + } + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListConnections(HttpClient httpClient) { + setup(httpClient); + + // Verify that listing connections returns results + Iterable connections = connectionsClient.listConnections(); + Assertions.assertNotNull(connections); + + // Verify that at least one connection can be retrieved if available + boolean hasAtLeastOneConnection = false; + for (Connection connection : connections) { + hasAtLeastOneConnection = true; + assertValidConnection(connection, null, null, null); + break; + } + + // Note: This test will pass even if there are no connections, + // as we're only verifying the API works correctly + System.out.println("Connection list retrieved successfully" + + (hasAtLeastOneConnection ? " with at least one connection" : " (empty list)")); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListConnectionsWithFilters(HttpClient httpClient) { + setup(httpClient); + + // Test listing connections with type filter + Iterable azureOpenAIConnections + = connectionsClient.listConnections(ConnectionType.AZURE_OPEN_AI, null); + Assertions.assertNotNull(azureOpenAIConnections); + + // Verify that all returned connections have the correct type + azureOpenAIConnections.forEach(connection -> { + assertValidConnection(connection, null, ConnectionType.AZURE_OPEN_AI, null); + }); + + // Test listing default connections + Iterable defaultConnections = connectionsClient.listConnections(null, true); + Assertions.assertNotNull(defaultConnections); + + // Verify that all returned connections are default connections + defaultConnections.forEach(connection -> { + assertValidConnection(connection, null, null, true); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetConnectionWithoutCredentials(HttpClient httpClient) { + setup(httpClient); + + String connectionName = Configuration.getGlobalConfiguration().get("TEST_CONNECTION_NAME", "agentaisearch2aqa"); + + try { + Connection connection = connectionsClient.getConnection(connectionName, false); + + // Verify the connection properties + assertValidConnection(connection, connectionName, null, null); + Assertions.assertNotNull(connection.getCredentials().getType()); + + System.out.println("Connection retrieved successfully: " + connection.getName()); + } catch (Exception e) { + // If the connection doesn't exist, this will throw a ResourceNotFoundException + // We'll handle this case by printing a message and passing the test + System.out.println("Connection not found: " + connectionName); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetConnectionWithCredentials(HttpClient httpClient) { + setup(httpClient); + + String connectionName = Configuration.getGlobalConfiguration().get("TEST_CONNECTION_NAME", "agentaisearch2aqa"); + + try { + Connection connection = connectionsClient.getConnectionWithCredentials(connectionName); + + // Verify the connection properties + assertValidConnection(connection, connectionName, null, null); + Assertions.assertNotNull(connection.getCredentials().getType()); + + System.out.println("Connection with credentials retrieved successfully: " + connection.getName()); + System.out.println("Credential type: " + connection.getCredentials().getType()); + } catch (Exception e) { + // If the connection doesn't exist, this will throw a ResourceNotFoundException + // We'll handle this case by printing a message and passing the test + System.out.println("Connection not found: " + connectionName); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DatasetsAsyncClientTest.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DatasetsAsyncClientTest.java new file mode 100644 index 000000000000..4db94863bce4 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DatasetsAsyncClientTest.java @@ -0,0 +1,246 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.DatasetVersion; +import com.azure.ai.projects.models.FileDatasetVersion; +import com.azure.ai.projects.models.PendingUploadRequest; +import com.azure.core.http.HttpClient; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import reactor.test.StepVerifier; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static com.azure.ai.projects.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class DatasetsAsyncClientTest extends ClientTestBase { + + private AIProjectClientBuilder clientBuilder; + private DatasetsAsyncClient datasetsAsyncClient; + + private void setup(HttpClient httpClient) { + clientBuilder = getClientBuilder(httpClient); + datasetsAsyncClient = clientBuilder.buildDatasetsAsyncClient(); + } + + /** + * Helper method to validate common properties of a DatasetVersion + * + * @param datasetVersion The dataset version to validate + * @param expectedName The expected name of the dataset + * @param expectedVersion The expected version string + */ + private void assertDatasetVersion(DatasetVersion datasetVersion, String expectedName, String expectedVersion) { + Assertions.assertNotNull(datasetVersion, "Dataset version should not be null"); + Assertions.assertEquals(expectedName, datasetVersion.getName(), "Dataset name should match expected value"); + Assertions.assertEquals(expectedVersion, datasetVersion.getVersion(), + "Dataset version should match expected value"); + Assertions.assertNotNull(datasetVersion.getType(), "Dataset type should not be null"); + } + + /** + * Helper method to validate common properties of a FileDatasetVersion + * + * @param fileDatasetVersion The file dataset version to validate + * @param expectedName The expected name of the dataset + * @param expectedVersion The expected version string + * @param expectedDataUri The expected data URI (optional) + */ + private void assertFileDatasetVersion(FileDatasetVersion fileDatasetVersion, String expectedName, + String expectedVersion, String expectedDataUri) { + assertDatasetVersion(fileDatasetVersion, expectedName, expectedVersion); + if (expectedDataUri != null) { + Assertions.assertEquals(expectedDataUri, fileDatasetVersion.getDataUri(), + "Dataset dataUri should match expected value"); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testCreateDatasetWithFile(HttpClient httpClient) throws FileNotFoundException, URISyntaxException { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersionString = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + Path filePath = getPath("product_info.md"); + + StepVerifier.create(datasetsAsyncClient.createDatasetWithFile(datasetName, datasetVersionString, filePath)) + .assertNext(createdDatasetVersion -> assertFileDatasetVersion(createdDatasetVersion, datasetName, + datasetVersionString, null)) + .verifyComplete(); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testCreateDatasetWithFolder(HttpClient httpClient) throws IOException, URISyntaxException { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "folder-dataset") + + UUID.randomUUID().toString().substring(0, 8); + String datasetVersionString = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + // Create a temporary folder with test files + Path tempFolder = Files.createTempDirectory("test-folder-dataset"); + Path file1 = tempFolder.resolve("file1.txt"); + Path file2 = tempFolder.resolve("file2.txt"); + Files.write(file1, "Test content 1".getBytes()); + Files.write(file2, "Test content 2".getBytes()); + + try { + StepVerifier + .create(datasetsAsyncClient.createDatasetWithFolder(datasetName, datasetVersionString, tempFolder)) + .assertNext(createdDatasetVersion -> assertDatasetVersion(createdDatasetVersion, datasetName, + datasetVersionString)) + .verifyComplete(); + } finally { + // Clean up temporary files + Files.deleteIfExists(file1); + Files.deleteIfExists(file2); + Files.deleteIfExists(tempFolder); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListDatasets(HttpClient httpClient) { + setup(httpClient); + + // Collect datasets into a list + List datasetsList = new ArrayList<>(); + + StepVerifier.create(datasetsAsyncClient.listLatestDatasetVersions().doOnNext(datasetsList::add).then()) + .verifyComplete(); + + // Verify we found at least one dataset + Assertions.assertFalse(datasetsList.isEmpty(), "Expected at least one dataset"); + + // Verify each dataset + for (DatasetVersion dataset : datasetsList) { + assertDatasetVersion(dataset, dataset.getName(), dataset.getVersion()); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListDatasetVersions(HttpClient httpClient) { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + + // Collect dataset versions into a list + List versionsList = new ArrayList<>(); + + StepVerifier.create(datasetsAsyncClient.listDatasetVersions(datasetName).doOnNext(versionsList::add).then()) + .verifyComplete(); + + // Verify we found at least one version + Assertions.assertFalse(versionsList.isEmpty(), "Expected at least one dataset version"); + + // Verify each version + for (DatasetVersion version : versionsList) { + assertDatasetVersion(version, datasetName, version.getVersion()); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetDataset(HttpClient httpClient) { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + StepVerifier.create(datasetsAsyncClient.getDatasetVersion(datasetName, datasetVersion)) + .assertNext(dataset -> assertDatasetVersion(dataset, datasetName, datasetVersion)) + .verifyComplete(); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testCreateOrUpdateDataset(HttpClient httpClient) { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "updated-dataset") + + UUID.randomUUID().toString().substring(0, 8); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + String dataUri = Configuration.getGlobalConfiguration().get("DATA_URI", "https://example.com/data.txt"); + + // Create a new FileDatasetVersion + FileDatasetVersion fileDataset + = new FileDatasetVersion().setDataUri(dataUri).setDescription("Test dataset created via SDK tests"); + + StepVerifier.create(datasetsAsyncClient.createOrUpdateDatasetVersion(datasetName, datasetVersion, fileDataset)) + .assertNext(createdDataset -> { + FileDatasetVersion fileDatasetVersion = (FileDatasetVersion) createdDataset; + assertFileDatasetVersion(fileDatasetVersion, datasetName, datasetVersion, dataUri); + Assertions.assertEquals("Test dataset created via SDK tests", fileDatasetVersion.getDescription()); + }) + .verifyComplete(); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testPendingUpload(HttpClient httpClient) { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "pending-upload-dataset") + + UUID.randomUUID().toString().substring(0, 8); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + // Create a pending upload request + PendingUploadRequest request = new PendingUploadRequest(); + + StepVerifier.create(datasetsAsyncClient.pendingUpload(datasetName, datasetVersion, request)) + .assertNext(response -> { + Assertions.assertNotNull(response); + Assertions.assertNotNull(response.getPendingUploadId()); + Assertions.assertNotNull(response.getBlobReference()); + Assertions.assertNotNull(response.getBlobReference().getBlobUri()); + Assertions.assertNotNull(response.getBlobReference().getCredential()); + }) + .verifyComplete(); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testDeleteDataset(HttpClient httpClient) throws FileNotFoundException, URISyntaxException { + setup(httpClient); + + // First create a dataset that we can then delete + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "delete-test-dataset") + + UUID.randomUUID().toString().substring(0, 8); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + Path filePath = getPath("product_info.md"); + + // Create and verify a dataset exists first + datasetsAsyncClient.createDatasetWithFile(datasetName, datasetVersion, filePath).block(); // We need to ensure the dataset is created before continuing + + // Delete the dataset + StepVerifier.create(datasetsAsyncClient.deleteDatasetVersion(datasetName, datasetVersion)).verifyComplete(); + + // Verify deletion - this should cause an error + StepVerifier.create(datasetsAsyncClient.getDatasetVersion(datasetName, datasetVersion)) + .expectErrorMatches(e -> e.getMessage().contains("404") || e.getMessage().contains("Not Found")) + .verify(); + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DatasetsClientTest.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DatasetsClientTest.java new file mode 100644 index 000000000000..bee2fe52123e --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DatasetsClientTest.java @@ -0,0 +1,244 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.DatasetVersion; +import com.azure.ai.projects.models.FileDatasetVersion; +import com.azure.ai.projects.models.FolderDatasetVersion; +import com.azure.ai.projects.models.PendingUploadRequest; +import com.azure.ai.projects.models.PendingUploadResponse; +import com.azure.core.http.HttpClient; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; + +import static com.azure.ai.projects.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class DatasetsClientTest extends ClientTestBase { + + private AIProjectClientBuilder clientBuilder; + private DatasetsClient datasetsClient; + + private void setup(HttpClient httpClient) { + clientBuilder = getClientBuilder(httpClient); + datasetsClient = clientBuilder.buildDatasetsClient(); + } + + /** + * Helper method to validate common properties of a DatasetVersion + * + * @param datasetVersion The dataset version to validate + * @param expectedName The expected name of the dataset + * @param expectedVersion The expected version string + */ + private void assertDatasetVersion(DatasetVersion datasetVersion, String expectedName, String expectedVersion) { + Assertions.assertNotNull(datasetVersion, "Dataset version should not be null"); + Assertions.assertEquals(expectedName, datasetVersion.getName(), "Dataset name should match expected value"); + Assertions.assertEquals(expectedVersion, datasetVersion.getVersion(), + "Dataset version should match expected value"); + Assertions.assertNotNull(datasetVersion.getType(), "Dataset type should not be null"); + } + + /** + * Helper method to validate common properties of a FileDatasetVersion + * + * @param fileDatasetVersion The file dataset version to validate + * @param expectedName The expected name of the dataset + * @param expectedVersion The expected version string + * @param expectedDataUri The expected data URI (optional) + */ + private void assertFileDatasetVersion(FileDatasetVersion fileDatasetVersion, String expectedName, + String expectedVersion, String expectedDataUri) { + assertDatasetVersion(fileDatasetVersion, expectedName, expectedVersion); + if (expectedDataUri != null) { + Assertions.assertEquals(expectedDataUri, fileDatasetVersion.getDataUri(), + "Dataset dataUri should match expected value"); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testCreateDatasetWithFile(HttpClient httpClient) throws FileNotFoundException, URISyntaxException { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersionString = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + Path filePath = getPath("product_info.md"); + + FileDatasetVersion createdDatasetVersion + = datasetsClient.createDatasetWithFile(datasetName, datasetVersionString, filePath); + + assertFileDatasetVersion(createdDatasetVersion, datasetName, datasetVersionString, null); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testCreateDatasetWithFolder(HttpClient httpClient) throws IOException, URISyntaxException { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "folder-dataset") + + UUID.randomUUID().toString().substring(0, 8); + String datasetVersionString = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + // Create a temporary folder with test files + Path tempFolder = Files.createTempDirectory("test-folder-dataset"); + Path file1 = tempFolder.resolve("file1.txt"); + Path file2 = tempFolder.resolve("file2.txt"); + Files.write(file1, "Test content 1".getBytes()); + Files.write(file2, "Test content 2".getBytes()); + + try { + FolderDatasetVersion createdDatasetVersion + = datasetsClient.createDatasetWithFolder(datasetName, datasetVersionString, tempFolder); + + assertDatasetVersion(createdDatasetVersion, datasetName, datasetVersionString); + } finally { + // Clean up temporary files + Files.deleteIfExists(file1); + Files.deleteIfExists(file2); + Files.deleteIfExists(tempFolder); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListDatasets(HttpClient httpClient) { + setup(httpClient); + + // Verify that listing datasets returns results + Iterable datasets = datasetsClient.listLatestDatasetVersions(); + Assertions.assertNotNull(datasets); + + // Verify that at least one dataset can be retrieved + // Note: This test assumes at least one dataset exists + datasets.forEach(dataset -> { + assertDatasetVersion(dataset, dataset.getName(), dataset.getVersion()); + }); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListDatasetVersions(HttpClient httpClient) { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + + // Verify that listing dataset versions returns results + Iterable versions = datasetsClient.listDatasetVersions(datasetName); + Assertions.assertNotNull(versions); + + // Verify that at least one dataset version can be retrieved + // Note: This test assumes the specified dataset exists with at least one version + versions.forEach(version -> { + assertDatasetVersion(version, datasetName, version.getVersion()); + }); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetDataset(HttpClient httpClient) { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "my-dataset"); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + // Get a specific dataset version + DatasetVersion dataset = datasetsClient.getDatasetVersion(datasetName, datasetVersion); + + // Verify the dataset properties + assertDatasetVersion(dataset, datasetName, datasetVersion); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testCreateOrUpdateDataset(HttpClient httpClient) { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "updated-dataset") + + UUID.randomUUID().toString().substring(0, 8); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + String dataUri = Configuration.getGlobalConfiguration().get("DATA_URI", "https://example.com/data.txt"); + + // Create a new FileDatasetVersion + FileDatasetVersion fileDataset + = new FileDatasetVersion().setDataUri(dataUri).setDescription("Test dataset created via SDK tests"); + + // Create or update the dataset + FileDatasetVersion createdDataset = (FileDatasetVersion) datasetsClient + .createOrUpdateDatasetVersion(datasetName, datasetVersion, fileDataset); + + // Verify the created dataset + assertFileDatasetVersion(createdDataset, datasetName, datasetVersion, dataUri); + Assertions.assertEquals("Test dataset created via SDK tests", createdDataset.getDescription()); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testPendingUpload(HttpClient httpClient) { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "pending-upload-dataset") + + UUID.randomUUID().toString().substring(0, 8); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + // Create a pending upload request + PendingUploadRequest request = new PendingUploadRequest(); + + // Get the pending upload response + PendingUploadResponse response = datasetsClient.pendingUpload(datasetName, datasetVersion, request); + + // Verify the response + Assertions.assertNotNull(response); + Assertions.assertNotNull(response.getPendingUploadId()); + Assertions.assertNotNull(response.getBlobReference()); + Assertions.assertNotNull(response.getBlobReference().getBlobUri()); + Assertions.assertNotNull(response.getBlobReference().getCredential()); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testDeleteDataset(HttpClient httpClient) throws FileNotFoundException, URISyntaxException { + setup(httpClient); + + // First create a dataset that we can then delete + String datasetName = Configuration.getGlobalConfiguration().get("DATASET_NAME", "delete-test-dataset") + + UUID.randomUUID().toString().substring(0, 8); + String datasetVersion = Configuration.getGlobalConfiguration().get("DATASET_VERSION", "1.0"); + + Path filePath = getPath("product_info.md"); + + // Create a dataset + FileDatasetVersion createdDataset = datasetsClient.createDatasetWithFile(datasetName, datasetVersion, filePath); + Assertions.assertNotNull(createdDataset); + + // Delete the dataset + datasetsClient.deleteDatasetVersion(datasetName, datasetVersion); + + // Verify deletion - this should throw ResourceNotFoundException + try { + datasetsClient.getDatasetVersion(datasetName, datasetVersion); + Assertions.fail("Expected ResourceNotFoundException was not thrown"); + } catch (Exception e) { + // Expected exception + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } + +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DeploymentsAsyncClientTest.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DeploymentsAsyncClientTest.java new file mode 100644 index 000000000000..db99a07be3eb --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DeploymentsAsyncClientTest.java @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.Deployment; +import com.azure.ai.projects.models.DeploymentType; +import com.azure.core.http.HttpClient; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import reactor.test.StepVerifier; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import static com.azure.ai.projects.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class DeploymentsAsyncClientTest extends ClientTestBase { + + private AIProjectClientBuilder clientBuilder; + private DeploymentsAsyncClient deploymentsAsyncClient; + + private void setup(HttpClient httpClient) { + clientBuilder = getClientBuilder(httpClient); + deploymentsAsyncClient = clientBuilder.buildDeploymentsAsyncClient(); + } + + /** + * Helper method to verify a Deployment has valid properties. + * @param deployment The deployment to validate + * @param expectedName The expected name of the deployment, or null if no specific name is expected + * @param expectedType The expected deployment type, or null if no specific type is expected + */ + private void assertValidDeployment(Deployment deployment, String expectedName, DeploymentType expectedType) { + Assertions.assertNotNull(deployment); + Assertions.assertNotNull(deployment.getName()); + Assertions.assertNotNull(deployment.getType()); + + if (expectedName != null) { + Assertions.assertEquals(expectedName, deployment.getName()); + } + + if (expectedType != null) { + Assertions.assertEquals(expectedType, deployment.getType()); + } + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListDeployments(HttpClient httpClient) { + setup(httpClient); + + // Verify that listing deployments returns results + PagedFlux deploymentsFlux = deploymentsAsyncClient.listDeployments(); + Assertions.assertNotNull(deploymentsFlux); + + // Collect all deployments and verify + List deployments = new ArrayList<>(); + deploymentsFlux.collectList().block(Duration.ofSeconds(30)); + + System.out.println("Deployment list retrieved successfully" + + (deployments.size() > 0 ? " with " + deployments.size() + " deployments" : " (empty list)")); + + // Verify the first deployment if available + StepVerifier.create(deploymentsFlux.take(1)) + .assertNext(deployment -> assertValidDeployment(deployment, null, null)) + .verifyComplete(); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListDeploymentsWithFilters(HttpClient httpClient) { + setup(httpClient); + + // Test listing deployments with model publisher filter + String testPublisher = "openai"; + PagedFlux publisherFilteredDeployments + = deploymentsAsyncClient.listDeployments(testPublisher, null, null); + Assertions.assertNotNull(publisherFilteredDeployments); + + // Verify filtered deployments + StepVerifier.create(publisherFilteredDeployments.take(10)).thenConsumeWhile(deployment -> { + assertValidDeployment(deployment, null, null); + System.out.println("Retrieved publisher-filtered deployment: " + deployment.getName()); + return true; + }).verifyComplete(); + + // Test listing deployments with model name filter + String testModelName = "gpt-4o-mini"; + PagedFlux modelNameFilteredDeployments + = deploymentsAsyncClient.listDeployments(null, testModelName, null); + Assertions.assertNotNull(modelNameFilteredDeployments); + + // Verify filtered deployments + StepVerifier.create(modelNameFilteredDeployments.take(10)).thenConsumeWhile(deployment -> { + assertValidDeployment(deployment, null, null); + System.out.println("Retrieved model-name-filtered deployment: " + deployment.getName()); + return true; + }).verifyComplete(); + + // Test listing deployments with deployment type filter + PagedFlux typeFilteredDeployments + = deploymentsAsyncClient.listDeployments(null, null, DeploymentType.MODEL_DEPLOYMENT); + Assertions.assertNotNull(typeFilteredDeployments); + + // Verify filtered deployments + StepVerifier.create(typeFilteredDeployments.take(10)).thenConsumeWhile(deployment -> { + assertValidDeployment(deployment, null, DeploymentType.MODEL_DEPLOYMENT); + System.out.println("Retrieved type-filtered deployment: " + deployment.getName()); + return true; + }).verifyComplete(); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetDeployment(HttpClient httpClient) { + setup(httpClient); + + String deploymentName = Configuration.getGlobalConfiguration().get("TEST_DEPLOYMENT_NAME", "gpt-4o-mini"); + + StepVerifier.create(deploymentsAsyncClient.getDeployment(deploymentName)).assertNext(deployment -> { + assertValidDeployment(deployment, deploymentName, null); + System.out.println("Deployment retrieved successfully: " + deployment.getName()); + }).verifyComplete(); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetDeploymentAndVerifyType(HttpClient httpClient) { + setup(httpClient); + + String deploymentName = Configuration.getGlobalConfiguration().get("TEST_DEPLOYMENT_NAME", "gpt-4o-mini"); + + StepVerifier.create(deploymentsAsyncClient.getDeployment(deploymentName)).assertNext(deployment -> { + assertValidDeployment(deployment, deploymentName, DeploymentType.MODEL_DEPLOYMENT); + System.out.println("Deployment type successfully verified for: " + deployment.getName()); + }).verifyComplete(); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetDeploymentNotFound(HttpClient httpClient) { + setup(httpClient); + + String nonExistentDeploymentName = "non-existent-deployment-name"; + + StepVerifier.create(deploymentsAsyncClient.getDeployment(nonExistentDeploymentName)) + .expectErrorMatches(error -> { + System.out.println("Expected error received: " + error.getMessage()); + return error.getMessage().contains("404") || error.getMessage().contains("Not Found"); + }) + .verify(); + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DeploymentsClientTest.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DeploymentsClientTest.java new file mode 100644 index 000000000000..e9032e45064c --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/DeploymentsClientTest.java @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.Deployment; +import com.azure.ai.projects.models.DeploymentType; +import com.azure.core.http.HttpClient; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static com.azure.ai.projects.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class DeploymentsClientTest extends ClientTestBase { + + private AIProjectClientBuilder clientBuilder; + private DeploymentsClient deploymentsClient; + + private void setup(HttpClient httpClient) { + clientBuilder = getClientBuilder(httpClient); + deploymentsClient = clientBuilder.buildDeploymentsClient(); + } + + /** + * Helper method to verify a Deployment has valid properties. + * @param deployment The deployment to validate + * @param expectedName The expected name of the deployment, or null if no specific name is expected + * @param expectedType The expected deployment type, or null if no specific type is expected + */ + private void assertValidDeployment(Deployment deployment, String expectedName, DeploymentType expectedType) { + Assertions.assertNotNull(deployment); + Assertions.assertNotNull(deployment.getName()); + Assertions.assertNotNull(deployment.getType()); + + if (expectedName != null) { + Assertions.assertEquals(expectedName, deployment.getName()); + } + + if (expectedType != null) { + Assertions.assertEquals(expectedType, deployment.getType()); + } + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListDeployments(HttpClient httpClient) { + setup(httpClient); + + // Verify that listing deployments returns results + Iterable deployments = deploymentsClient.listDeployments(); + Assertions.assertNotNull(deployments); + + // Verify that at least one deployment can be retrieved if available + boolean hasAtLeastOneDeployment = false; + for (Deployment deployment : deployments) { + hasAtLeastOneDeployment = true; + assertValidDeployment(deployment, null, null); + break; + } + + // Note: This test will pass even if there are no deployments, + // as we're only verifying the API works correctly + System.out.println("Deployment list retrieved successfully" + + (hasAtLeastOneDeployment ? " with at least one deployment" : " (empty list)")); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListDeploymentsWithFilters(HttpClient httpClient) { + setup(httpClient); + + // Test listing deployments with model publisher filter + String testPublisher = "openai"; + Iterable filteredDeployments = deploymentsClient.listDeployments(testPublisher, null, null); + Assertions.assertNotNull(filteredDeployments); + + // Test listing deployments with model name filter + String testModelName = "gpt-4o-mini"; + Iterable modelNameFilteredDeployments + = deploymentsClient.listDeployments(null, testModelName, null); + Assertions.assertNotNull(modelNameFilteredDeployments); + + // Test listing deployments with deployment type filter + Iterable typeFilteredDeployments + = deploymentsClient.listDeployments(null, null, DeploymentType.MODEL_DEPLOYMENT); + Assertions.assertNotNull(typeFilteredDeployments); + + // Verify that all returned deployments have the correct type + typeFilteredDeployments.forEach(deployment -> { + assertValidDeployment(deployment, null, DeploymentType.MODEL_DEPLOYMENT); + }); + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetDeployment(HttpClient httpClient) { + setup(httpClient); + + String deploymentName = Configuration.getGlobalConfiguration().get("TEST_DEPLOYMENT_NAME", "gpt-4o-mini"); + + try { + Deployment deployment = deploymentsClient.getDeployment(deploymentName); + + // Verify the deployment properties + assertValidDeployment(deployment, deploymentName, null); + + System.out.println("Deployment retrieved successfully: " + deployment.getName()); + System.out.println("Deployment type: " + deployment.getType().getValue()); + } catch (Exception e) { + // If the deployment doesn't exist, this will throw a ResourceNotFoundException + // We'll handle this case by printing a message and passing the test + System.out.println("Deployment not found: " + deploymentName); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } + + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetDeploymentAndVerifyType(HttpClient httpClient) { + setup(httpClient); + + String deploymentName = Configuration.getGlobalConfiguration().get("TEST_DEPLOYMENT_NAME", "gpt-4o-mini"); + + try { + Deployment deployment = deploymentsClient.getDeployment(deploymentName); + + // Verify the deployment properties + assertValidDeployment(deployment, deploymentName, DeploymentType.MODEL_DEPLOYMENT); + + System.out.println("Deployment type successfully verified for: " + deployment.getName()); + } catch (Exception e) { + // If the deployment doesn't exist, this will throw a ResourceNotFoundException + // We'll handle this case by printing a message and passing the test + System.out.println("Deployment not found for type verification test: " + deploymentName); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/EvaluationsAsyncClientTest.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/EvaluationsAsyncClientTest.java new file mode 100644 index 000000000000..c2bc48c80838 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/EvaluationsAsyncClientTest.java @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.DatasetVersion; +import com.azure.ai.projects.models.Evaluation; +import com.azure.ai.projects.models.EvaluatorConfiguration; +import com.azure.ai.projects.models.EvaluatorId; +import com.azure.ai.projects.models.InputDataset; +import com.azure.core.http.HttpClient; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +import static com.azure.ai.projects.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class EvaluationsAsyncClientTest extends ClientTestBase { + + private AIProjectClientBuilder clientBuilder; + private EvaluationsAsyncClient evaluationsAsyncClient; + private DatasetsAsyncClient datasetsAsyncClient; + + private void setup(HttpClient httpClient) { + clientBuilder = getClientBuilder(httpClient); + evaluationsAsyncClient = clientBuilder.buildEvaluationsAsyncClient(); + datasetsAsyncClient = clientBuilder.buildDatasetsAsyncClient(); + } + + /** + * Helper method to verify an Evaluation has valid properties. + * @param evaluation The evaluation to validate + * @param expectedDisplayName The expected display name of the evaluation, or null if no specific name is expected + * @param expectedStatus The expected status, or null if no specific status is expected + */ + private void assertValidEvaluation(Evaluation evaluation, String expectedDisplayName, String expectedStatus) { + Assertions.assertNotNull(evaluation); + Assertions.assertNotNull(evaluation.getDisplayName()); + Assertions.assertNotNull(evaluation.getStatus()); + Assertions.assertNotNull(evaluation.getData()); + Assertions.assertNotNull(evaluation.getData().getType()); + Assertions.assertNotNull(evaluation.getEvaluators()); + Assertions.assertFalse(evaluation.getEvaluators().isEmpty()); + + if (expectedDisplayName != null) { + Assertions.assertEquals(expectedDisplayName, evaluation.getDisplayName()); + } + + if (expectedStatus != null) { + Assertions.assertEquals(expectedStatus, evaluation.getStatus()); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListEvaluationsAsync(HttpClient httpClient) { + setup(httpClient); + + // Verify that listing evaluations returns results + AtomicBoolean hasAtLeastOneEvaluation = new AtomicBoolean(false); + + StepVerifier.create(evaluationsAsyncClient.listEvaluations().take(1)).assertNext(evaluation -> { + hasAtLeastOneEvaluation.set(true); + assertValidEvaluation(evaluation, null, null); + }).verifyComplete(); + + // Note: This test will pass even if there are no evaluations, + // as we're only verifying the API works correctly + System.out.println("Evaluation list retrieved successfully" + + (hasAtLeastOneEvaluation.get() ? " with at least one evaluation" : " (empty list)")); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetEvaluationAsync(HttpClient httpClient) { + setup(httpClient); + + String evaluationId = Configuration.getGlobalConfiguration().get("TEST_EVALUATION_ID", "test-evaluation-id"); + + StepVerifier.create(evaluationsAsyncClient.getEvaluation(evaluationId).doOnNext(evaluation -> { + // Verify the evaluation properties + assertValidEvaluation(evaluation, null, null); + + if (evaluation.getTags() != null) { + // Verify tags are properly structured if present + evaluation.getTags().forEach((key, value) -> { + Assertions.assertNotNull(key); + Assertions.assertNotNull(value); + }); + } + + System.out.println("Evaluation retrieved successfully: " + evaluation.getDisplayName()); + System.out.println("Status: " + evaluation.getStatus()); + }).timeout(Duration.ofSeconds(30))).verifyComplete(); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testCreateEvaluationAsync(HttpClient httpClient) { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("TEST_DATASET_NAME", "test-dataset"); + String version = Configuration.getGlobalConfiguration().get("TEST_DATASET_VERSION", "1"); + + // Get a dataset to use for the evaluation + Mono datasetVersionMono = datasetsAsyncClient.getDatasetVersion(datasetName, version); + + StepVerifier.create(datasetVersionMono.flatMap(datasetVersion -> { + // Create evaluation definition + InputDataset dataset = new InputDataset(datasetVersion.getId()); + Evaluation evaluationToCreate = new Evaluation(dataset, + mapOf("relevance", + new EvaluatorConfiguration(EvaluatorId.RELEVANCE.getValue()) + .setInitParams(mapOf("deployment_name", BinaryData.fromObject("gpt-4o"))))) + .setDisplayName("Test Async Evaluation " + System.currentTimeMillis()) + .setDescription("This is a test evaluation created by the EvaluationsAsyncClientTest"); + + // Create the evaluation + return evaluationsAsyncClient.createEvaluation(evaluationToCreate); + })).assertNext(createdEvaluation -> { + // Verify the created evaluation + assertValidEvaluation(createdEvaluation, null, null); + Assertions.assertTrue(createdEvaluation.getDisplayName().startsWith("Test Async Evaluation")); + Assertions.assertTrue(createdEvaluation.getEvaluators().containsKey("relevance")); + + System.out.println("Evaluation created successfully: " + createdEvaluation.getDisplayName()); + System.out.println("Initial status: " + createdEvaluation.getStatus()); + }).verifyComplete(); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testEvaluationStatusCheckAsync(HttpClient httpClient) { + setup(httpClient); + + String evaluationId = Configuration.getGlobalConfiguration().get("TEST_EVALUATION_ID", "test-evaluation-id"); + + StepVerifier.create(evaluationsAsyncClient.getEvaluation(evaluationId)).assertNext(evaluation -> { + // Verify status is one of the expected values + Assertions.assertNotNull(evaluation.getStatus()); + String status = evaluation.getStatus(); + + // Status should be one of: Running, Succeeded, Failed, Canceled, etc. + boolean isValidStatus = "Running".equals(status) + || "Succeeded".equals(status) + || "Failed".equals(status) + || "Canceled".equals(status) + || "Queued".equals(status) + || "Created".equals(status); + + Assertions.assertTrue(isValidStatus, "Unexpected evaluation status: " + status); + + System.out.println("Evaluation status check passed: " + status); + }).verifyComplete(); + } + + // Helper method for creating maps + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + @SuppressWarnings("unchecked") + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/EvaluationsClientTest.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/EvaluationsClientTest.java new file mode 100644 index 000000000000..714385eb3fae --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/EvaluationsClientTest.java @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.DatasetVersion; +import com.azure.ai.projects.models.Evaluation; +import com.azure.ai.projects.models.EvaluatorConfiguration; +import com.azure.ai.projects.models.EvaluatorId; +import com.azure.ai.projects.models.InputDataset; +import com.azure.core.http.HttpClient; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import java.util.HashMap; +import java.util.Map; + +import static com.azure.ai.projects.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class EvaluationsClientTest extends ClientTestBase { + + private AIProjectClientBuilder clientBuilder; + private EvaluationsClient evaluationsClient; + private DatasetsClient datasetsClient; + + private void setup(HttpClient httpClient) { + clientBuilder = getClientBuilder(httpClient); + evaluationsClient = clientBuilder.buildEvaluationsClient(); + datasetsClient = clientBuilder.buildDatasetsClient(); + } + + /** + * Helper method to verify an Evaluation has valid properties. + * @param evaluation The evaluation to validate + * @param expectedDisplayName The expected display name of the evaluation, or null if no specific name is expected + * @param expectedStatus The expected status, or null if no specific status is expected + */ + private void assertValidEvaluation(Evaluation evaluation, String expectedDisplayName, String expectedStatus) { + Assertions.assertNotNull(evaluation); + Assertions.assertNotNull(evaluation.getDisplayName()); + Assertions.assertNotNull(evaluation.getStatus()); + Assertions.assertNotNull(evaluation.getData()); + Assertions.assertNotNull(evaluation.getData().getType()); + Assertions.assertNotNull(evaluation.getEvaluators()); + Assertions.assertFalse(evaluation.getEvaluators().isEmpty()); + + if (expectedDisplayName != null) { + Assertions.assertEquals(expectedDisplayName, evaluation.getDisplayName()); + } + + if (expectedStatus != null) { + Assertions.assertEquals(expectedStatus, evaluation.getStatus()); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListEvaluations(HttpClient httpClient) { + setup(httpClient); + + // Verify that listing evaluations returns results + Iterable evaluations = evaluationsClient.listEvaluations(); + Assertions.assertNotNull(evaluations); + + // Verify that at least one evaluation can be retrieved if available + boolean hasAtLeastOneEvaluation = false; + for (Evaluation evaluation : evaluations) { + hasAtLeastOneEvaluation = true; + assertValidEvaluation(evaluation, null, null); + break; + } + + // Note: This test will pass even if there are no evaluations, + // as we're only verifying the API works correctly + System.out.println("Evaluation list retrieved successfully" + + (hasAtLeastOneEvaluation ? " with at least one evaluation" : " (empty list)")); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetEvaluation(HttpClient httpClient) { + setup(httpClient); + + String evaluationId = Configuration.getGlobalConfiguration().get("TEST_EVALUATION_ID", "test-evaluation-id"); + + try { + Evaluation evaluation = evaluationsClient.getEvaluation(evaluationId); + + // Verify the evaluation properties + assertValidEvaluation(evaluation, null, null); + + if (evaluation.getTags() != null) { + // Verify tags are properly structured if present + evaluation.getTags().forEach((key, value) -> { + Assertions.assertNotNull(key); + Assertions.assertNotNull(value); + }); + } + + System.out.println("Evaluation retrieved successfully: " + evaluation.getDisplayName()); + System.out.println("Status: " + evaluation.getStatus()); + } catch (Exception e) { + // If the evaluation doesn't exist, this will throw a ResourceNotFoundException + // We'll handle this case by printing a message and passing the test + System.out.println("Evaluation not found: " + evaluationId); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testCreateEvaluation(HttpClient httpClient) { + setup(httpClient); + + String datasetName = Configuration.getGlobalConfiguration().get("TEST_DATASET_NAME", "test-dataset"); + String version = Configuration.getGlobalConfiguration().get("TEST_DATASET_VERSION", "1"); + + try { + // Get a dataset to use for the evaluation + DatasetVersion datasetVersion = datasetsClient.getDatasetVersion(datasetName, version); + + // Create evaluation definition + InputDataset dataset = new InputDataset(datasetVersion.getId()); + Evaluation evaluationToCreate = new Evaluation(dataset, + mapOf("relevance", + new EvaluatorConfiguration(EvaluatorId.RELEVANCE.getValue()) + .setInitParams(mapOf("deployment_name", BinaryData.fromObject("gpt-4o"))))) + .setDisplayName("Test Evaluation " + System.currentTimeMillis()) + .setDescription("This is a test evaluation created by the EvaluationsClientTest"); + + // Create the evaluation + Evaluation createdEvaluation = evaluationsClient.createEvaluation(evaluationToCreate); + + // Verify the created evaluation + assertValidEvaluation(createdEvaluation, evaluationToCreate.getDisplayName(), null); + Assertions.assertEquals(evaluationToCreate.getDescription(), createdEvaluation.getDescription()); + Assertions.assertTrue(createdEvaluation.getEvaluators().containsKey("relevance")); + + System.out.println("Evaluation created successfully: " + createdEvaluation.getDisplayName()); + System.out.println("Initial status: " + createdEvaluation.getStatus()); + } catch (Exception e) { + // If the dataset doesn't exist or there's another issue + System.out.println("Failed to create evaluation: " + e.getMessage()); + throw e; + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testEvaluationStatusCheck(HttpClient httpClient) { + setup(httpClient); + + String evaluationId = Configuration.getGlobalConfiguration().get("TEST_EVALUATION_ID", "test-evaluation-id"); + + try { + Evaluation evaluation = evaluationsClient.getEvaluation(evaluationId); + + // Verify status is one of the expected values + Assertions.assertNotNull(evaluation.getStatus()); + String status = evaluation.getStatus(); + + // Status should be one of: Running, Succeeded, Failed, Canceled, etc. + boolean isValidStatus = "Running".equals(status) + || "Succeeded".equals(status) + || "Failed".equals(status) + || "Canceled".equals(status) + || "Queued".equals(status) + || "Created".equals(status); + + Assertions.assertTrue(isValidStatus, "Unexpected evaluation status: " + status); + + System.out.println("Evaluation status check passed: " + status); + } catch (Exception e) { + // If the evaluation doesn't exist, this will throw a ResourceNotFoundException + System.out.println("Evaluation not found for status check: " + evaluationId); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } + + // Helper method for creating maps + private static Map mapOf(Object... inputs) { + Map map = new HashMap<>(); + for (int i = 0; i < inputs.length; i += 2) { + String key = (String) inputs[i]; + @SuppressWarnings("unchecked") + T value = (T) inputs[i + 1]; + map.put(key, value); + } + return map; + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/IndexesAsyncClientTest.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/IndexesAsyncClientTest.java new file mode 100644 index 000000000000..2cb2576f960b --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/IndexesAsyncClientTest.java @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.AzureAISearchIndex; +import com.azure.ai.projects.models.Index; +import com.azure.core.http.HttpClient; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import static com.azure.ai.projects.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class IndexesAsyncClientTest extends ClientTestBase { + + private AIProjectClientBuilder clientBuilder; + private IndexesAsyncClient indexesAsyncClient; + + private void setup(HttpClient httpClient) { + clientBuilder = getClientBuilder(httpClient); + indexesAsyncClient = clientBuilder.buildIndexesAsyncClient(); + } + + /** + * Helper method to verify an Index has valid properties. + * @param index The index to validate + * @param expectedName The expected name of the index, or null if no specific name is expected + * @param expectedVersion The expected version of the index, or null if no specific version is expected + */ + private void assertValidIndex(Index index, String expectedName, String expectedVersion) { + Assertions.assertNotNull(index); + Assertions.assertNotNull(index.getName()); + Assertions.assertNotNull(index.getVersion()); + Assertions.assertNotNull(index.getType()); + + if (expectedName != null) { + Assertions.assertEquals(expectedName, index.getName()); + } + + if (expectedVersion != null) { + Assertions.assertEquals(expectedVersion, index.getVersion()); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListIndexesAsync(HttpClient httpClient) { + setup(httpClient); + + // Collect indexes into a list for verification + List indexList = new ArrayList<>(); + + // Verify that listing indexes returns results + StepVerifier.create(indexesAsyncClient.listLatestIndexVersions().doOnNext(index -> { + indexList.add(index); + assertValidIndex(index, null, null); + })).expectComplete().verify(Duration.ofMinutes(1)); + + System.out.println("Index list retrieved successfully" + + (indexList.isEmpty() ? " (empty list)" : " with " + indexList.size() + " index(es)")); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListIndexVersionsAsync(HttpClient httpClient) { + setup(httpClient); + + String indexName = Configuration.getGlobalConfiguration().get("TEST_INDEX_NAME", "test-index"); + List versionList = new ArrayList<>(); + + // Verify that listing index versions returns results or appropriate error + StepVerifier.create(indexesAsyncClient.listIndexVersions(indexName).doOnNext(index -> { + versionList.add(index); + assertValidIndex(index, indexName, null); + }).onErrorResume(e -> { + // If the index doesn't exist, this will throw a ResourceNotFoundException + // We'll handle this case by printing a message + System.out.println("Index not found for version listing: " + indexName); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + return Mono.empty(); + })).expectComplete().verify(Duration.ofMinutes(1)); + + System.out.println("Index versions for '" + indexName + "' retrieved successfully" + + (versionList.isEmpty() ? " (empty list)" : " with " + versionList.size() + " version(s)")); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetIndexAsync(HttpClient httpClient) { + setup(httpClient); + + String indexName = Configuration.getGlobalConfiguration().get("TEST_INDEX_NAME", "test-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("TEST_INDEX_VERSION", "1.0"); + + StepVerifier.create(indexesAsyncClient.getIndexVersion(indexName, indexVersion).doOnNext(index -> { + // Verify the index properties + assertValidIndex(index, indexName, indexVersion); + System.out + .println("Index retrieved successfully: " + index.getName() + " (version " + index.getVersion() + ")"); + System.out.println("Index type: " + index.getType()); + }).onErrorResume(e -> { + // If the index doesn't exist, this will throw a ResourceNotFoundException + System.out.println("Index not found: " + indexName + " (version " + indexVersion + ")"); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + return Mono.empty(); + })).expectComplete().verify(Duration.ofMinutes(1)); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testCreateOrUpdateIndexAsync(HttpClient httpClient) { + setup(httpClient); + + // Configuration for creating/updating an index + String indexName = Configuration.getGlobalConfiguration().get("TEST_INDEX_NAME", "test-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("TEST_INDEX_VERSION", "1.0"); + String aiSearchConnectionName + = Configuration.getGlobalConfiguration().get("TEST_AI_SEARCH_CONNECTION_NAME", "test-search-connection"); + String aiSearchIndexName + = Configuration.getGlobalConfiguration().get("TEST_AI_SEARCH_INDEX_NAME", "test-search-index"); + + // Create an AzureAISearchIndex + AzureAISearchIndex searchIndex + = new AzureAISearchIndex().setConnectionName(aiSearchConnectionName).setIndexName(aiSearchIndexName); + + StepVerifier.create(indexesAsyncClient.createOrUpdateIndexVersion(indexName, indexVersion, searchIndex) + .doOnNext(createdIndex -> { + // Verify the created/updated index + assertValidIndex(createdIndex, indexName, indexVersion); + + // Verify it's the correct type + Assertions.assertTrue(createdIndex instanceof AzureAISearchIndex); + AzureAISearchIndex createdSearchIndex = (AzureAISearchIndex) createdIndex; + Assertions.assertEquals(aiSearchConnectionName, createdSearchIndex.getConnectionName()); + Assertions.assertEquals(aiSearchIndexName, createdSearchIndex.getIndexName()); + + System.out.println("Index created/updated successfully: " + createdIndex.getName() + " (version " + + createdIndex.getVersion() + ")"); + })).expectNextCount(1).expectComplete().verify(Duration.ofMinutes(1)); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testDeleteIndexAsync(HttpClient httpClient) { + setup(httpClient); + + String indexName = Configuration.getGlobalConfiguration().get("TEST_INDEX_NAME", "test-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("TEST_INDEX_VERSION", "1.0"); + + // First verify the index exists + indexesAsyncClient.getIndexVersion(indexName, indexVersion) + .doOnNext(index -> assertValidIndex(index, indexName, indexVersion)) + .flatMap(index -> indexesAsyncClient.deleteIndexVersion(indexName, indexVersion)) + .doOnSuccess(unused -> System.out.println("Index deletion request submitted")) + .then(Mono.delay(Duration.ofSeconds(2))) // Give some time for the deletion to complete + .then(indexesAsyncClient.getIndexVersion(indexName, indexVersion)) + .doOnNext(deletedIndex -> Assertions + .fail("Index should have been deleted but was found: " + deletedIndex.getName())) + .onErrorResume(e -> { + // Expected exception + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + System.out.println("Index successfully deleted: " + indexName + " (version " + indexVersion + ")"); + return Mono.empty(); + }) + .onErrorResume(e -> { + // If the index doesn't exist already for the initial get, this is fine + System.out.println("Index not found for deletion: " + indexName + " (version " + indexVersion + ")"); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + return Mono.empty(); + }) + .block(Duration.ofMinutes(1)); + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/IndexesClientTest.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/IndexesClientTest.java new file mode 100644 index 000000000000..6e884a703846 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/IndexesClientTest.java @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.ai.projects.models.AzureAISearchIndex; +import com.azure.ai.projects.models.Index; +import com.azure.core.http.HttpClient; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static com.azure.ai.projects.TestUtils.DISPLAY_NAME_WITH_ARGUMENTS; + +public class IndexesClientTest extends ClientTestBase { + + private AIProjectClientBuilder clientBuilder; + private IndexesClient indexesClient; + + private void setup(HttpClient httpClient) { + clientBuilder = getClientBuilder(httpClient); + indexesClient = clientBuilder.buildIndexesClient(); + } + + /** + * Helper method to verify an Index has valid properties. + * @param index The index to validate + * @param expectedName The expected name of the index, or null if no specific name is expected + * @param expectedVersion The expected version of the index, or null if no specific version is expected + */ + private void assertValidIndex(Index index, String expectedName, String expectedVersion) { + Assertions.assertNotNull(index); + Assertions.assertNotNull(index.getName()); + Assertions.assertNotNull(index.getVersion()); + Assertions.assertNotNull(index.getType()); + + if (expectedName != null) { + Assertions.assertEquals(expectedName, index.getName()); + } + + if (expectedVersion != null) { + Assertions.assertEquals(expectedVersion, index.getVersion()); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListIndexes(HttpClient httpClient) { + setup(httpClient); + + // Verify that listing indexes returns results + Iterable indexes = indexesClient.listLatestIndexVersions(); + Assertions.assertNotNull(indexes); + + // Verify that at least one index can be retrieved if available + boolean hasAtLeastOneIndex = false; + for (Index index : indexes) { + hasAtLeastOneIndex = true; + assertValidIndex(index, null, null); + break; + } + + // Note: This test will pass even if there are no indexes, + // as we're only verifying the API works correctly + System.out.println( + "Index list retrieved successfully" + (hasAtLeastOneIndex ? " with at least one index" : " (empty list)")); + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testListIndexVersions(HttpClient httpClient) { + setup(httpClient); + + String indexName = Configuration.getGlobalConfiguration().get("TEST_INDEX_NAME", "test-index"); + + try { + // Verify that listing index versions returns results + Iterable indexVersions = indexesClient.listIndexVersions(indexName); + Assertions.assertNotNull(indexVersions); + + // Verify that at least one index version can be retrieved if available + boolean hasAtLeastOneVersion = false; + for (Index index : indexVersions) { + hasAtLeastOneVersion = true; + assertValidIndex(index, indexName, null); + break; + } + + System.out.println("Index versions for '" + indexName + "' retrieved successfully" + + (hasAtLeastOneVersion ? " with at least one version" : " (empty list)")); + } catch (Exception e) { + // If the index doesn't exist, this will throw a ResourceNotFoundException + // We'll handle this case by printing a message and passing the test + System.out.println("Index not found for version listing: " + indexName); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testGetIndex(HttpClient httpClient) { + setup(httpClient); + + String indexName = Configuration.getGlobalConfiguration().get("TEST_INDEX_NAME", "test-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("TEST_INDEX_VERSION", "1.0"); + + try { + Index index = indexesClient.getIndexVersion(indexName, indexVersion); + + // Verify the index properties + assertValidIndex(index, indexName, indexVersion); + + System.out + .println("Index retrieved successfully: " + index.getName() + " (version " + index.getVersion() + ")"); + System.out.println("Index type: " + index.getType()); + } catch (Exception e) { + // If the index doesn't exist, this will throw a ResourceNotFoundException + // We'll handle this case by printing a message and passing the test + System.out.println("Index not found: " + indexName + " (version " + indexVersion + ")"); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testCreateOrUpdateIndex(HttpClient httpClient) { + setup(httpClient); + + // Configuration for creating/updating an index + String indexName = Configuration.getGlobalConfiguration().get("TEST_INDEX_NAME", "test-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("TEST_INDEX_VERSION", "1.0"); + String aiSearchConnectionName + = Configuration.getGlobalConfiguration().get("TEST_AI_SEARCH_CONNECTION_NAME", "test-search-connection"); + String aiSearchIndexName + = Configuration.getGlobalConfiguration().get("TEST_AI_SEARCH_INDEX_NAME", "test-search-index"); + + try { + // Create an AzureAISearchIndex + AzureAISearchIndex searchIndex + = new AzureAISearchIndex().setConnectionName(aiSearchConnectionName).setIndexName(aiSearchIndexName); + + // Create or update the index + Index createdIndex = indexesClient.createOrUpdateIndexVersion(indexName, indexVersion, searchIndex); + + // Verify the created/updated index + assertValidIndex(createdIndex, indexName, indexVersion); + + // Verify it's the correct type + Assertions.assertTrue(createdIndex instanceof AzureAISearchIndex); + AzureAISearchIndex createdSearchIndex = (AzureAISearchIndex) createdIndex; + Assertions.assertEquals(aiSearchConnectionName, createdSearchIndex.getConnectionName()); + Assertions.assertEquals(aiSearchIndexName, createdSearchIndex.getIndexName()); + + System.out.println("Index created/updated successfully: " + createdIndex.getName() + " (version " + + createdIndex.getVersion() + ")"); + } catch (Exception e) { + System.out.println("Failed to create/update index: " + e.getMessage()); + throw e; + } + } + + @Disabled + @ParameterizedTest(name = DISPLAY_NAME_WITH_ARGUMENTS) + @MethodSource("com.azure.ai.projects.TestUtils#getTestParameters") + public void testDeleteIndex(HttpClient httpClient) { + setup(httpClient); + + String indexName = Configuration.getGlobalConfiguration().get("TEST_INDEX_NAME", "test-index"); + String indexVersion = Configuration.getGlobalConfiguration().get("TEST_INDEX_VERSION", "1.0"); + + try { + // First verify the index exists + Index index = indexesClient.getIndexVersion(indexName, indexVersion); + assertValidIndex(index, indexName, indexVersion); + + // Delete the index + indexesClient.deleteIndexVersion(indexName, indexVersion); + + // Try to get the deleted index - should throw ResourceNotFoundException + try { + Index deletedIndex = indexesClient.getIndexVersion(indexName, indexVersion); + Assertions.fail("Index should have been deleted but was found: " + deletedIndex.getName()); + } catch (Exception e) { + // Expected exception + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + System.out.println("Index successfully deleted: " + indexName + " (version " + indexVersion + ")"); + } + } catch (Exception e) { + // If the index doesn't exist already, this is fine for the test + System.out.println("Index not found for deletion: " + indexName + " (version " + indexVersion + ")"); + Assertions.assertTrue(e.getMessage().contains("404") || e.getMessage().contains("Not Found")); + } + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/TestUtils.java b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/TestUtils.java new file mode 100644 index 000000000000..f7e87dc39b50 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/java/com/azure/ai/projects/TestUtils.java @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.projects; + +import com.azure.core.http.HttpClient; +import org.junit.jupiter.params.provider.Arguments; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import static com.azure.core.test.TestBase.getHttpClients; + +public class TestUtils { + + static final String DISPLAY_NAME_WITH_ARGUMENTS = "{displayName} with [{arguments}]"; + static final String FAKE_API_KEY = "fakeKeyPlaceholder"; + + /** + * Returns a stream of arguments that includes all combinations of eligible {@link HttpClient HttpClients} + * that should be tested. + * + * @return A stream of HttpClients to test. + */ + static Stream getTestParameters() { + // when this issues is closed, the newer version of junit will have better support for + // cartesian product of arguments - https://github.com/junit-team/junit5/issues/1427 + List argumentsList = new ArrayList<>(); + getHttpClients().forEach(httpClient -> argumentsList.add(Arguments.of(httpClient))); + return argumentsList.stream(); + } +} diff --git a/sdk/ai/azure-ai-projects/src/test/resources/product_info.md b/sdk/ai/azure-ai-projects/src/test/resources/product_info.md new file mode 100644 index 000000000000..041155831d53 --- /dev/null +++ b/sdk/ai/azure-ai-projects/src/test/resources/product_info.md @@ -0,0 +1,51 @@ +# Information about product item_number: 1 + +## Brand +Contoso Galaxy Innovations + +## Category +Smart Eyewear + +## Features +- Augmented Reality interface +- Voice-controlled AI assistant +- HD video recording with 3D audio +- UV protection and blue light filtering +- Wireless charging with extended battery life + +## User Guide + +### 1. Introduction +Introduction to your new SmartView Glasses + +### 2. Product Overview +Overview of features and controls + +### 3. Sizing and Fit +Finding your perfect fit and style adjustments + +### 4. Proper Care and Maintenance +Cleaning and caring for your SmartView Glasses + +### 5. Break-in Period +Adjusting to the augmented reality experience + +### 6. Safety Tips +Safety guidelines for public and private spaces + +### 7. Troubleshooting +Quick fixes for common issues + +## Warranty Information +Two-year limited warranty on all electronic components + +## Contact Information +Customer Support at support@contoso-galaxy-innovations.com + +## Return Policy +30-day return policy with no questions asked + +## FAQ +- How to sync your SmartView Glasses with your devices +- Troubleshooting connection issues +- Customizing your augmented reality environment diff --git a/sdk/ai/azure-ai-projects/tsp-location.yaml b/sdk/ai/azure-ai-projects/tsp-location.yaml new file mode 100644 index 000000000000..e1bb605d1c77 --- /dev/null +++ b/sdk/ai/azure-ai-projects/tsp-location.yaml @@ -0,0 +1,5 @@ +directory: specification/ai/Azure.AI.Projects/ +commit: 1fee81eaffe2963de3457923ada416af6891f94b +repo: Azure/azure-rest-api-specs +additionalDirectories: [] + diff --git a/sdk/ai/ci.yml b/sdk/ai/ci.yml index 395df95f01ba..d0f8706957ae 100644 --- a/sdk/ai/ci.yml +++ b/sdk/ai/ci.yml @@ -34,6 +34,10 @@ parameters: displayName: 'azure-ai-inference' type: boolean default: true + - name: release_azureaiprojects + displayName: 'azure-ai-projects' + type: boolean + default: false - name: release_azureaiagentspersistent displayName: 'azure-ai-agents-persistent' type: boolean @@ -48,6 +52,10 @@ extends: groupId: com.azure safeName: azureaiinference releaseInBatch: ${{ parameters.release_azureaiinference }} + - name: azure-ai-projects + groupId: com.azure + safeName: azureaiprojects + releaseInBatch: ${{ parameters.release_azureaiprojects }} - name: azure-ai-agents-persistent groupId: com.azure safeName: azureaiagentspersistent diff --git a/sdk/ai/pom.xml b/sdk/ai/pom.xml index 340fed2e6346..24fde9dca725 100644 --- a/sdk/ai/pom.xml +++ b/sdk/ai/pom.xml @@ -11,6 +11,7 @@ azure-ai-inference + azure-ai-projects azure-ai-agents-persistent