diff --git a/.vscode/cspell.json b/.vscode/cspell.json index 6c164c64981e..44661ee315cf 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -476,7 +476,9 @@ "TGIANT", "tiktoken", "AITOKENS", - "Matryoshka" + "Matryoshka", + "OMINI", + "resyncing" ] }, { diff --git a/eng/code-quality-reports/src/main/resources/revapi/revapi.json b/eng/code-quality-reports/src/main/resources/revapi/revapi.json index 3c913f810b61..45334d12e5f4 100644 --- a/eng/code-quality-reports/src/main/resources/revapi/revapi.json +++ b/eng/code-quality-reports/src/main/resources/revapi/revapi.json @@ -757,6 +757,36 @@ "new": "method void com.azure.search.documents.indexes.models.SearchResourceEncryptionKey::(java.lang.String, java.lang.String)", "justification": "Breaking change in Search 03-01-2025 preview." }, + { + "ignore": true, + "code": "java.method.visibilityIncreased", + "old": "method reactor.core.publisher.Mono> com.azure.search.documents.SearchAsyncClient::getDocumentWithResponse(java.lang.String, java.lang.Class, java.util.List, com.azure.core.util.Context)", + "justification": "Non-breaking change in Search 05-01-2025 preview to package-private api." + }, + { + "ignore": true, + "code": "java.method.visibilityIncreased", + "old": "method reactor.core.publisher.Mono com.azure.search.documents.SearchAsyncClient::search(com.azure.search.documents.implementation.models.SearchRequest, java.lang.String, com.azure.search.documents.implementation.models.SearchFirstPageResponseWrapper, com.azure.core.util.Context)", + "justification": "Non-breaking change in Search 05-01-2025 preview to package-private api." + }, + { + "ignore": true, + "code": "java.method.visibilityIncreased", + "old": "method com.azure.search.documents.util.SearchPagedFlux com.azure.search.documents.SearchAsyncClient::search(java.lang.String, com.azure.search.documents.models.SearchOptions, com.azure.core.util.Context)", + "justification": "Non-breaking change in Search 05-01-2025 preview to package-private api." + }, + { + "ignore": true, + "code": "java.method.visibilityIncreased", + "old": "method com.azure.search.documents.util.SearchPagedResponse com.azure.search.documents.SearchClient::search(com.azure.search.documents.implementation.models.SearchRequest, java.lang.String, com.azure.search.documents.implementation.models.SearchFirstPageResponseWrapper, com.azure.core.util.Context)", + "justification": "Non-breaking change in Search 05-01-2025 preview to package-private api." + }, + { + "ignore": true, + "code": "java.method.visibilityIncreased", + "old": "method com.azure.search.documents.util.SearchPagedFlux com.azure.search.documents.SearchAsyncClient::search(com.azure.search.documents.implementation.models.SearchRequest, java.lang.String, com.azure.core.util.Context)", + "justification": "Non-breaking change in Search 05-01-2025 preview to package-private api." + }, { "regex": true, "code": "java.field.enumConstantOrderChanged", diff --git a/sdk/search/azure-search-documents/CHANGELOG.md b/sdk/search/azure-search-documents/CHANGELOG.md index 82fd4bb5397a..08d4bc11a6d8 100644 --- a/sdk/search/azure-search-documents/CHANGELOG.md +++ b/sdk/search/azure-search-documents/CHANGELOG.md @@ -1,14 +1,19 @@ # Release History -## 11.8.0-beta.7 (Unreleased) +## 11.8.0-beta.7 (2025-05-16) ### Features Added -### Breaking Changes - -### Bugs Fixed - -### Other Changes +- Added new `KnowledgeAgent` apis to index clients and introduced new `SearchKnowledgeAgentClient` for managing and querying Knowledge Agents, +enabling multi-index grounding for agentic retrieval. +- Added a method overloads for search client operations to include the `querySourceAuthentication` parameter, allowing users to specify the authentication method for the query source. +- Added a `resync` method to indexer clients to resync selective options from the data source to be re-ingested by the indexer. +- Added `permissionFilter` to Field Builder annotations, indication whether a field should be used as a permission filter. +- Added `rerankerBoostedScore` to `SemanticSearchResult` and updated `SemanticConfiguration` with a new `rankingOrder` property. +- Introduced new skill `ChatCompletionSkill` that integrates with Azure AI Foundry. +- Enhanced `DocumentIntelligenceLayoutSkill` with new properties: `ChunkingProperties`, `ExtractionOptions`, and `OutputFormat`. +- Added `IndexerPermissionOptions` to `SearchIndexerDataSourceConnection` to support ingestion of various types of permission data. +- Introduced sub-field vector support (multi-vectors) via `VectorQuery.Fields`, and added new query option `VectorQuery.PerDocumentVectorLimit`. ## 11.8.0-beta.6 (2025-04-17) diff --git a/sdk/search/azure-search-documents/README.md b/sdk/search/azure-search-documents/README.md index 3a6e6875df06..ccc3c7e4de82 100644 --- a/sdk/search/azure-search-documents/README.md +++ b/sdk/search/azure-search-documents/README.md @@ -75,7 +75,7 @@ add the direct dependency to your project as follows. com.azure azure-search-documents - 11.8.0-beta.6 + 11.8.0-beta.7 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/search/azure-search-documents/assets.json b/sdk/search/azure-search-documents/assets.json index e80a466435b0..bf72e32f2250 100644 --- a/sdk/search/azure-search-documents/assets.json +++ b/sdk/search/azure-search-documents/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/search/azure-search-documents", - "Tag": "java/search/azure-search-documents_8d90b12483" + "Tag": "java/search/azure-search-documents_ab303259b0" } diff --git a/sdk/search/azure-search-documents/checkstyle-suppressions.xml b/sdk/search/azure-search-documents/checkstyle-suppressions.xml index c4c1ae64c7b3..96fd82fb896b 100644 --- a/sdk/search/azure-search-documents/checkstyle-suppressions.xml +++ b/sdk/search/azure-search-documents/checkstyle-suppressions.xml @@ -65,4 +65,6 @@ + + diff --git a/sdk/search/azure-search-documents/pom.xml b/sdk/search/azure-search-documents/pom.xml index caa38629c1c8..f4bc9a2c53d1 100644 --- a/sdk/search/azure-search-documents/pom.xml +++ b/sdk/search/azure-search-documents/pom.xml @@ -24,8 +24,8 @@ UTF-8 - 0.52 - 0.42 + 0.46 + 0.40 --add-exports com.azure.core/com.azure.core.implementation.http=ALL-UNNAMED diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java index daa7f5fb344f..81a9f4ecad30 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java @@ -858,7 +858,42 @@ Mono> indexDocumentsWithResponse(IndexDocumentsBa */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getDocument(String key, Class modelClass) { - return getDocumentWithResponse(key, modelClass, null).map(Response::getValue); + return getDocumentWithResponse(key, modelClass, null, null).map(Response::getValue); + } + + /** + * Retrieves a document from the Azure AI Search index. + *

+ * View naming rules for guidelines on + * constructing valid document keys. + * + *

Code Sample

+ * + *

Get dynamic SearchDocument.

+ * + * + *
+     * SEARCH_ASYNC_CLIENT.getDocument("hotelId", SearchDocument.class)
+     *     .subscribe(result -> {
+     *         for (Map.Entry<String, Object> keyValuePair : result.entrySet()) {
+     *             System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(),
+     *                 keyValuePair.getValue());
+     *         }
+     *     });
+     * 
+ * + * + * @param key The key of the document to retrieve. + * @param modelClass The model class converts to. + * @param querySourceAuthorization Token identifying the user for which the query is being executed. + * This token is used to enforce security restrictions on documents. + * @param Convert document to the generic type. + * @return the document object + * @see Lookup document + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getDocument(String key, Class modelClass, String querySourceAuthorization) { + return getDocumentWithResponse(key, modelClass, null, querySourceAuthorization).map(Response::getValue); } /** @@ -894,14 +929,54 @@ public Mono getDocument(String key, Class modelClass) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getDocumentWithResponse(String key, Class modelClass, List selectedFields) { - return withContext(context -> getDocumentWithResponse(key, modelClass, selectedFields, context)); + return withContext(context -> getDocumentWithResponse(key, modelClass, selectedFields, null, context)); + } + + /** + * Retrieves a document from the Azure AI Search index. + *

+ * View naming rules for guidelines on + * constructing valid document keys. + * + *

Code Sample

+ * + *

Get dynamic SearchDocument.

+ * + * + *
+     * SEARCH_ASYNC_CLIENT.getDocumentWithResponse("hotelId", SearchDocument.class, null)
+     *     .subscribe(resultResponse -> {
+     *         System.out.println("The status code of the response is " + resultResponse.getStatusCode());
+     *         for (Map.Entry<String, Object> keyValuePair : resultResponse.getValue().entrySet()) {
+     *             System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(),
+     *                 keyValuePair.getValue());
+     *         }
+     *     });
+     * 
+ * + * + * @param Convert document to the generic type. + * @param key The key of the document to retrieve. + * @param modelClass The model class converts to. + * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will have null or + * default as its corresponding property value in the returned object. + * @param querySourceAuthorization Token identifying the user for which the query is being executed. + * This token is used to enforce security restrictions on documents. + * @return a response containing the document object + * @see Lookup document + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getDocumentWithResponse(String key, Class modelClass, List selectedFields, + String querySourceAuthorization) { + return withContext( + context -> getDocumentWithResponse(key, modelClass, selectedFields, querySourceAuthorization, context)); } Mono> getDocumentWithResponse(String key, Class modelClass, List selectedFields, - Context context) { + String querySourceAuthorization, Context context) { try { return restClient.getDocuments() - .getWithResponseAsync(key, selectedFields, null, context) + .getWithResponseAsync(key, selectedFields, querySourceAuthorization, null, context) .onErrorMap(Utility::exceptionMapper) .map(res -> new SimpleResponse<>(res, serializer .deserializeFromBytes(serializer.serializeToBytes(res.getValue()), createInstance(modelClass)))); @@ -1020,7 +1095,66 @@ Mono> getDocumentCountWithResponse(Context context) { */ @ServiceMethod(returns = ReturnType.COLLECTION) public SearchPagedFlux search(String searchText) { - return this.search(searchText, null); + return this.search(searchText, null, null); + } + + /** + * Searches for documents in the Azure AI Search index. + *

+ * If {@code searchText} is set to null or {@code "*"} all documents will be matched, see + * simple query + * syntax in Azure AI Search for more information about search query syntax. + *

+ * The {@link SearchPagedFlux} will iterate through search result pages until all search results are returned. + * Each page is determined by the {@code $skip} and {@code $top} values and the Search service has a limit on the + * number of documents that can be skipped, more information about the {@code $skip} limit can be found at + * Search Documents REST API and + * reading the {@code $skip} description. If the total number of results exceeds the {@code $skip} limit the + * {@link SearchPagedFlux} won't prevent you from exceeding the {@code $skip} limit. To prevent exceeding the limit + * you can track the number of documents returned and stop requesting new pages when the limit is reached. + * + *

Code Sample

+ * + *

Search text from documents in service.

+ * + * + *
+     * SearchPagedFlux searchPagedFlux = SEARCH_ASYNC_CLIENT.search("searchText");
+     * searchPagedFlux.getTotalCount().subscribe(
+     *     count -> System.out.printf("There are around %d results.", count));
+     *
+     * AtomicLong numberOfDocumentsReturned = new AtomicLong();
+     * searchPagedFlux.byPage()
+     *     .takeUntil(page -> {
+     *         if (numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT) {
+     *             // Reached the $skip limit, stop requesting more documents.
+     *             return true;
+     *         }
+     *
+     *         return false;
+     *     })
+     *     .subscribe(resultResponse -> {
+     *         for (SearchResult result: resultResponse.getValue()) {
+     *             SearchDocument searchDocument = result.getDocument(SearchDocument.class);
+     *             for (Map.Entry<String, Object> keyValuePair: searchDocument.entrySet()) {
+     *                 System.out.printf("Document key %s, document value %s", keyValuePair.getKey(), keyValuePair.getValue());
+     *             }
+     *         }
+     *     });
+     * 
+ * + * + * @param searchText A full-text search query expression. + * @param querySourceAuthorization Token identifying the user for which the query is being executed. + * This token is used to enforce security restrictions on documents. + * @return A {@link SearchPagedFlux} that iterates over {@link SearchResult} objects and provides access to the + * {@link SearchPagedResponse} object for each page containing HTTP response and count, facet, and coverage + * information. + * @see Search documents + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public SearchPagedFlux search(String searchText, String querySourceAuthorization) { + return this.search(searchText, null, querySourceAuthorization, null); } /** @@ -1078,27 +1212,87 @@ public SearchPagedFlux search(String searchText) { */ @ServiceMethod(returns = ReturnType.COLLECTION) public SearchPagedFlux search(String searchText, SearchOptions searchOptions) { + return search(searchText, searchOptions, null); + } + + /** + * Searches for documents in the Azure AI Search index. + *

+ * If {@code searchText} is set to null or {@code "*"} all documents will be matched, see + * simple query + * syntax in Azure AI Search for more information about search query syntax. + *

+ * The {@link SearchPagedFlux} will iterate through search result pages until all search results are returned. + * Each page is determined by the {@code $skip} and {@code $top} values and the Search service has a limit on the + * number of documents that can be skipped, more information about the {@code $skip} limit can be found at + * Search Documents REST API and + * reading the {@code $skip} description. If the total number of results exceeds the {@code $skip} limit the + * {@link SearchPagedFlux} won't prevent you from exceeding the {@code $skip} limit. To prevent exceeding the limit + * you can track the number of documents returned and stop requesting new pages when the limit is reached. + * + *

Code Sample

+ * + *

Search text from documents in service with option.

+ * + * + *
+     * SearchPagedFlux pagedFlux = SEARCH_ASYNC_CLIENT.search("searchText",
+     *     new SearchOptions().setOrderBy("hotelId desc"));
+     *
+     * pagedFlux.getTotalCount().subscribe(count -> System.out.printf("There are around %d results.", count));
+     *
+     * AtomicLong numberOfDocumentsReturned = new AtomicLong();
+     * pagedFlux.byPage()
+     *     .takeUntil(page -> {
+     *         if (numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT) {
+     *             // Reached the $skip limit, stop requesting more documents.
+     *             return true;
+     *         }
+     *
+     *         return false;
+     *     })
+     *     .subscribe(searchResultResponse -> searchResultResponse.getValue().forEach(searchDocument -> {
+     *         for (Map.Entry<String, Object> keyValuePair
+     *             : searchDocument.getDocument(SearchDocument.class).entrySet()) {
+     *             System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
+     *                 keyValuePair.getValue());
+     *         }
+     *     }));
+     * 
+ * + * + * @param searchText A full-text search query expression. + * @param searchOptions Parameters to further refine the search query + * @param querySourceAuthorization Token identifying the user for which the query is being executed. + * @return A {@link SearchPagedFlux} that iterates over {@link SearchResult} objects and provides access to the + * {@link SearchPagedResponse} object for each page containing HTTP response and count, facet, and coverage + * information. + * @see Search documents + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public SearchPagedFlux search(String searchText, SearchOptions searchOptions, String querySourceAuthorization) { SearchRequest request = createSearchRequest(searchText, searchOptions); // The firstPageResponse shared among all functional calls below. // Do not initial new instance directly in func call. final SearchFirstPageResponseWrapper firstPageResponse = new SearchFirstPageResponseWrapper(); Function> func = continuationToken -> withContext( - context -> search(request, continuationToken, firstPageResponse, context)); + context -> search(request, continuationToken, firstPageResponse, querySourceAuthorization, context)); return new SearchPagedFlux(() -> func.apply(null), func); } - SearchPagedFlux search(String searchText, SearchOptions searchOptions, Context context) { + SearchPagedFlux search(String searchText, SearchOptions searchOptions, String querySourceAuthorization, + Context context) { SearchRequest request = createSearchRequest(searchText, searchOptions); // The firstPageResponse shared among all functional calls below. // Do not initial new instance directly in func call. final SearchFirstPageResponseWrapper firstPageResponseWrapper = new SearchFirstPageResponseWrapper(); - Function> func - = continuationToken -> search(request, continuationToken, firstPageResponseWrapper, context); + Function> func = continuationToken -> search(request, continuationToken, + firstPageResponseWrapper, querySourceAuthorization, context); return new SearchPagedFlux(() -> func.apply(null), func); } private Mono search(SearchRequest request, String continuationToken, - SearchFirstPageResponseWrapper firstPageResponseWrapper, Context context) { + SearchFirstPageResponseWrapper firstPageResponseWrapper, String querySourceAuthorization, Context context) { if (continuationToken == null && firstPageResponseWrapper.getFirstPageResponse() != null) { return Mono.just(firstPageResponseWrapper.getFirstPageResponse()); } @@ -1107,7 +1301,7 @@ private Mono search(SearchRequest request, String continuat : SearchContinuationToken.deserializeToken(serviceVersion.getVersion(), continuationToken); return restClient.getDocuments() - .searchPostWithResponseAsync(requestToUse, null, context) + .searchPostWithResponseAsync(requestToUse, querySourceAuthorization, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(response -> { SearchDocumentsResult result = response.getValue(); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java index f7f8e5842f50..c2d2aa7b3bd3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java @@ -832,10 +832,48 @@ public T getDocument(String key, Class modelClass) { @ServiceMethod(returns = ReturnType.SINGLE) public Response getDocumentWithResponse(String key, Class modelClass, List selectedFields, Context context) { + return getDocumentWithResponse(key, modelClass, selectedFields, null, context); + } + + /** + * Retrieves a document from the Azure AI Search index. + *

+ * View naming rules for guidelines on + * constructing valid document keys. + * + *

Code Sample

+ * + *

Get dynamic SearchDocument.

+ * + * + *
+     * Response<SearchDocument> resultResponse = SEARCH_CLIENT.getDocumentWithResponse("hotelId",
+     *     SearchDocument.class, null, new Context(KEY_1, VALUE_1));
+     * System.out.println("The status code of the response is " + resultResponse.getStatusCode());
+     * for (Map.Entry<String, Object> keyValuePair : resultResponse.getValue().entrySet()) {
+     *     System.out.printf("Document key %s, Document value %s", keyValuePair.getKey(), keyValuePair.getValue());
+     * }
+     * 
+ * + * + * @param Convert document to the generic type. + * @param key The key of the document to retrieve. + * @param modelClass The model class converts to. + * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will have null or + * default as its corresponding property value in the returned object. + * @param querySourceAuthorization Token identifying the user for which the query is being executed. + * This token is used to enforce security restrictions on documents. + * @param context additional context that is passed through the Http pipeline during the service call + * @return response containing a document object + * @see Lookup document + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getDocumentWithResponse(String key, Class modelClass, List selectedFields, + String querySourceAuthorization, Context context) { try { - Response> response - = restClient.getDocuments().getWithResponse(key, selectedFields, null, context); + Response> response = restClient.getDocuments() + .getWithResponse(key, selectedFields, querySourceAuthorization, null, context); return new SimpleResponse<>(response, serializer .deserializeFromBytes(serializer.serializeToBytes(response.getValue()), createInstance(modelClass))); @@ -1001,17 +1039,78 @@ public SearchPagedIterable search(String searchText) { */ @ServiceMethod(returns = ReturnType.COLLECTION) public SearchPagedIterable search(String searchText, SearchOptions searchOptions, Context context) { + return search(searchText, searchOptions, null, context); + } + + /** + * Searches for documents in the Azure AI Search index. + *

+ * If {@code searchText} is set to null or {@code "*"} all documents will be matched, see + * simple query + * syntax in Azure AI Search for more information about search query syntax. + *

+ * The {@link SearchPagedIterable} will iterate through search result pages until all search results are returned. + * Each page is determined by the {@code $skip} and {@code $top} values and the Search service has a limit on the + * number of documents that can be skipped, more information about the {@code $skip} limit can be found at + * Search Documents REST API and + * reading the {@code $skip} description. If the total number of results exceeds the {@code $skip} limit the + * {@link SearchPagedIterable} won't prevent you from exceeding the {@code $skip} limit. To prevent exceeding the + * limit you can track the number of documents returned and stop requesting new pages when the limit is reached. + * + *

Code Sample

+ * + *

Search text from documents in service with option.

+ * + * + *
+     * SearchPagedIterable searchPagedIterable = SEARCH_CLIENT.search("searchText",
+     *     new SearchOptions().setOrderBy("hotelId desc"), new Context(KEY_1, VALUE_1));
+     * System.out.printf("There are around %d results.", searchPagedIterable.getTotalCount());
+     *
+     * long numberOfDocumentsReturned = 0;
+     * for (SearchPagedResponse resultResponse: searchPagedIterable.iterableByPage()) {
+     *     System.out.println("The status code of the response is " + resultResponse.getStatusCode());
+     *     numberOfDocumentsReturned += resultResponse.getValue().size();
+     *     resultResponse.getValue().forEach(searchResult -> {
+     *         for (Map.Entry<String, Object> keyValuePair: searchResult
+     *             .getDocument(SearchDocument.class).entrySet()) {
+     *             System.out.printf("Document key %s, document value %s", keyValuePair.getKey(),
+     *                 keyValuePair.getValue());
+     *         }
+     *     });
+     *
+     *     if (numberOfDocumentsReturned >= SEARCH_SKIP_LIMIT) {
+     *         // Reached the $skip limit, stop requesting more documents.
+     *         break;
+     *     }
+     * }
+     * 
+ * + * + * @param searchText A full-text search query expression. + * @param searchOptions Parameters to further refine the search query + * @param querySourceAuthorization Token identifying the user for which the query is being executed. + * This token is used to enforce security restrictions on documents. + * @param context additional context that is passed through the Http pipeline during the service call + * @return A {@link SearchPagedIterable} that iterates over {@link SearchResult} objects and provides access to the + * {@link SearchPagedResponse} object for each page containing HTTP response and count, facet, and coverage + * information. + * @see Search documents + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public SearchPagedIterable search(String searchText, SearchOptions searchOptions, String querySourceAuthorization, + Context context) { SearchRequest request = createSearchRequest(searchText, searchOptions); // The firstPageResponse shared among all functional calls below. // Do not initial new instance directly in func call. final SearchFirstPageResponseWrapper firstPageResponseWrapper = new SearchFirstPageResponseWrapper(); - Function func - = continuationToken -> search(request, continuationToken, firstPageResponseWrapper, context); + Function func = continuationToken -> search(request, continuationToken, + firstPageResponseWrapper, querySourceAuthorization, context); return new SearchPagedIterable(() -> func.apply(null), func); } private SearchPagedResponse search(SearchRequest request, String continuationToken, - SearchFirstPageResponseWrapper firstPageResponseWrapper, Context context) { + SearchFirstPageResponseWrapper firstPageResponseWrapper, String querySourceAuthorization, Context context) { if (continuationToken == null && firstPageResponseWrapper.getFirstPageResponse() != null) { return firstPageResponseWrapper.getFirstPageResponse(); } @@ -1020,8 +1119,8 @@ private SearchPagedResponse search(SearchRequest request, String continuationTok : SearchContinuationToken.deserializeToken(serviceVersion.getVersion(), continuationToken); return Utility.executeRestCallWithExceptionHandling(() -> { - Response response - = restClient.getDocuments().searchPostWithResponse(requestToUse, null, context); + Response response = restClient.getDocuments() + .searchPostWithResponse(requestToUse, querySourceAuthorization, null, context); SearchDocumentsResult result = response.getValue(); SearchPagedResponse page = new SearchPagedResponse(new SimpleResponse<>(response, getSearchResults(result, serializer)), diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java index 599b3bd2d504..e33367e2e280 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceVersion.java @@ -27,7 +27,7 @@ public enum SearchServiceVersion implements ServiceVersion { /** * {@code 2024-11-01-preview} service version. */ - V2025_03_01_PREVIEW("2025-03-01-preview"); + V2025_05_01_PREVIEW("2025-05-01-preview"); private final String version; @@ -49,6 +49,6 @@ public String getVersion() { * @return The latest version supported by this client library. */ public static SearchServiceVersion getLatest() { - return V2025_03_01_PREVIEW; + return V2025_05_01_PREVIEW; } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/SearchKnowledgeAgentAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/SearchKnowledgeAgentAsyncClient.java new file mode 100644 index 000000000000..c07a8186787f --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/SearchKnowledgeAgentAsyncClient.java @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.agents; + +import static com.azure.core.util.FluxUtil.monoError; +import static com.azure.core.util.FluxUtil.withContext; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.search.documents.SearchServiceVersion; +import com.azure.search.documents.agents.implementation.KnowledgeAgentRetrievalClientImpl; +import com.azure.search.documents.agents.implementation.KnowledgeRetrievalsImpl; +import com.azure.search.documents.agents.models.KnowledgeAgentRetrievalRequest; +import com.azure.search.documents.agents.models.KnowledgeAgentRetrievalResponse; +import com.azure.search.documents.implementation.util.MappingUtils; + +import reactor.core.publisher.Mono; + +/** + * This class provides an asynchronous client for interacting with Azure AI Search Knowledge Agents, enabling retrieval of knowledge and data from various configured backing stores. + * + *

Overview

+ *

+ * The {@code SearchKnowledgeAgentAsyncClient} exposes asynchronous APIs for sending retrieval requests to a knowledge agent in Azure AI Search. The agent can aggregate and return relevant data from multiple sources, such as Azure AI Search indexes, vector stores, and other knowledge bases configured in your Azure AI Search instance. + *

+ * + *

Getting Started

+ *

+ * Instances of this client are created via the {@link SearchKnowledgeAgentClientBuilder}, which supports fluent configuration of credentials, endpoints, agent names, API versions, and other client options. Authentication can be performed using either an API key or Azure Active Directory credentials. The builder allows you to specify all required parameters for your scenario. + *

+ * + *

Thread Safety

+ *

+ * This client is thread-safe and intended to be shared and reused across threads. Client instances are immutable and do not maintain any mutable state. + *

+ * + *

Additional Information

+ *
    + *
  • For more information about Azure AI Search Knowledge Agents, see the Azure documentation.
  • + *
  • For authentication details, see the Azure AI Search security documentation.
  • + *
  • For Azure SDK for Java guidelines, see the Azure SDK for Java Introduction.
  • + *
+ * + * @see SearchKnowledgeAgentClientBuilder + * @see SearchKnowledgeAgentClient + * @see com.azure.search.documents.agents + */ +@ServiceClient(builder = SearchKnowledgeAgentClientBuilder.class, isAsync = true) +public final class SearchKnowledgeAgentAsyncClient { + private static final ClientLogger LOGGER = new ClientLogger(SearchKnowledgeAgentAsyncClient.class); + + private final String endpoint; + private final String agentName; + private final SearchServiceVersion serviceVersion; + private final HttpPipeline httpPipeline; + private final KnowledgeAgentRetrievalClientImpl impl; + private final KnowledgeRetrievalsImpl retrievals; + + /** + * Package-private constructor to be used by {@link SearchKnowledgeAgentClientBuilder}. + */ + SearchKnowledgeAgentAsyncClient(String endpoint, String agentName, SearchServiceVersion serviceVersion, + HttpPipeline httpPipeline) { + this.endpoint = endpoint; + this.agentName = agentName; + this.serviceVersion = serviceVersion; + this.httpPipeline = httpPipeline; + this.impl + = new KnowledgeAgentRetrievalClientImpl(httpPipeline, endpoint, agentName, serviceVersion.getVersion()); + this.retrievals = impl.getKnowledgeRetrievals(); + } + + /** + * Gets the endpoint for the Azure AI Search service. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Gets the agent name. + * + * @return the agentName value. + */ + public String getAgentName() { + return this.agentName; + } + + /** + * Gets the API version. + * + * @return the apiVersion value. + */ + public SearchServiceVersion getServiceVersion() { + return this.serviceVersion; + } + + /** + * Gets the {@link HttpPipeline} powering this client. + * + * @return the pipeline. + */ + public HttpPipeline getHttpPipeline() { + return this.httpPipeline; + } + + /** + * Asynchronously retrieves relevant data from backing stores. + * + * @param retrievalRequest The retrieval request to process. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. + * @return a {@link Mono} emitting the output contract for the retrieval response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono retrieve(KnowledgeAgentRetrievalRequest retrievalRequest, + String xMsQuerySourceAuthorization) { + return retrievals.retrieveAsync(retrievalRequest, xMsQuerySourceAuthorization, null); + } + + /** + * Asynchronously retrieves relevant data from backing stores, with a full HTTP response. + * + * @param retrievalRequest The retrieval request to process. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. + * @return a {@link Mono} emitting the output contract for the retrieval response along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> + retrieveWithResponse(KnowledgeAgentRetrievalRequest retrievalRequest, String xMsQuerySourceAuthorization) { + return withContext(context -> retrieveWithResponse(retrievalRequest, xMsQuerySourceAuthorization, context)); + } + + Mono> retrieveWithResponse( + KnowledgeAgentRetrievalRequest retrievalRequest, String xMsQuerySourceAuthorization, Context context) { + try { + return retrievals.retrieveWithResponseAsync(retrievalRequest, xMsQuerySourceAuthorization, null, context) + .onErrorMap(MappingUtils::exceptionMapper); + } catch (RuntimeException e) { + return monoError(LOGGER, e); + } + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/SearchKnowledgeAgentClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/SearchKnowledgeAgentClient.java new file mode 100644 index 000000000000..8c1070061915 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/SearchKnowledgeAgentClient.java @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.agents; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.search.documents.SearchServiceVersion; +import com.azure.search.documents.agents.implementation.KnowledgeAgentRetrievalClientImpl; +import com.azure.search.documents.agents.implementation.KnowledgeRetrievalsImpl; +import com.azure.search.documents.agents.models.KnowledgeAgentRetrievalRequest; +import com.azure.search.documents.agents.models.KnowledgeAgentRetrievalResponse; + +/** + * This class provides a client that contains the operations for retrieving knowledge from an Azure AI Search agent. + * + *

Overview

+ *

+ * The {@code SearchKnowledgeAgentClient} provides a synchronous API for interacting with Azure AI Search knowledge agents. This client enables you to send retrieval requests to a knowledge agent, which can aggregate and return relevant data from various backing stores configured in your Azure AI Search instance. + *

+ * + *

+ * The client is designed to be instantiated via the {@link SearchKnowledgeAgentClientBuilder}, which allows for fluent configuration of credentials, endpoints, agent names, and other client options. Once built, the client exposes methods to perform retrieval operations, returning structured responses that include the agent's results and any associated metadata. + *

+ * + *

Getting Started

+ *

+ * To get started, configure and build an instance of this client using the {@link SearchKnowledgeAgentClientBuilder}. Authentication can be performed using either an API key or Azure Active Directory credentials, and the builder allows you to specify the agent name, endpoint, and API version as required by your scenario. + *

+ * + *

Thread Safety

+ *

+ * This client is thread-safe and intended to be shared across threads and reused for multiple requests. + *

+ * + *

Additional Information

+ *

+ * For more information about Azure AI Search knowledge agents, see the Azure documentation. For advanced scenarios, such as customizing the HTTP pipeline or integrating with other Azure SDK components, refer to the Azure SDK for Java design guidelines and the documentation for {@link SearchKnowledgeAgentClientBuilder}. + *

+ * + * @see SearchKnowledgeAgentClientBuilder + * @see SearchKnowledgeAgentAsyncClient + */ +@ServiceClient(builder = SearchKnowledgeAgentClientBuilder.class) +public final class SearchKnowledgeAgentClient { + private static final ClientLogger LOGGER = new ClientLogger(SearchKnowledgeAgentClient.class); + + private final String endpoint; + private final String agentName; + private final SearchServiceVersion serviceVersion; + private final HttpPipeline httpPipeline; + private final KnowledgeAgentRetrievalClientImpl impl; + private final KnowledgeRetrievalsImpl retrievals; + + /** + * Package-private constructor to be used by {@link SearchKnowledgeAgentClientBuilder}. + */ + SearchKnowledgeAgentClient(String endpoint, String agentName, SearchServiceVersion serviceVersion, + HttpPipeline httpPipeline) { + this.endpoint = endpoint; + this.agentName = agentName; + this.serviceVersion = serviceVersion; + this.httpPipeline = httpPipeline; + this.impl + = new KnowledgeAgentRetrievalClientImpl(httpPipeline, endpoint, agentName, serviceVersion.getVersion()); + this.retrievals = impl.getKnowledgeRetrievals(); + } + + /** + * Gets the endpoint for the Azure AI Search service. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Gets the agent name. + * + * @return the agentName value. + */ + public String getAgentName() { + return this.agentName; + } + + /** + * Gets the API version. + * + * @return the apiVersion value. + */ + public SearchServiceVersion getServiceVersion() { + return this.serviceVersion; + } + + /** + * Gets the {@link HttpPipeline} powering this client. + * + * @return the pipeline. + */ + public HttpPipeline getHttpPipeline() { + return this.httpPipeline; + } + + /** + * Retrieves relevant data from backing stores synchronously. + * + * @param retrievalRequest The retrieval request to process. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. + * @return the output contract for the retrieval response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeAgentRetrievalResponse retrieve(KnowledgeAgentRetrievalRequest retrievalRequest, + String xMsQuerySourceAuthorization) { + return retrievals.retrieve(retrievalRequest, xMsQuerySourceAuthorization, null); + } + + /** + * Retrieves relevant data from backing stores synchronously, with a full HTTP response. + * + * @param retrievalRequest The retrieval request to process. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. + * @param context The context to associate with this operation. + * @return the output contract for the retrieval response along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response retrieveWithResponse( + KnowledgeAgentRetrievalRequest retrievalRequest, String xMsQuerySourceAuthorization, Context context) { + return retrievals.retrieveWithResponse(retrievalRequest, xMsQuerySourceAuthorization, null, context); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/SearchKnowledgeAgentClientBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/SearchKnowledgeAgentClientBuilder.java new file mode 100644 index 000000000000..a6332e1878e8 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/SearchKnowledgeAgentClientBuilder.java @@ -0,0 +1,247 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.agents; + +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.client.traits.AzureKeyCredentialTrait; +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.AzureKeyCredential; +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.core.http.policy.RetryOptions; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.util.ClientOptions; +import com.azure.core.util.Configuration; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.serializer.JsonSerializer; +import com.azure.search.documents.SearchServiceVersion; +import com.azure.search.documents.implementation.util.Utility; +import com.azure.search.documents.models.SearchAudience; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * This class provides a fluent builder API to help configure and instantiate {@link SearchKnowledgeAgentClient} + * and {@link SearchKnowledgeAgentAsyncClient} for interacting with Azure AI Search Knowledge Agents. + * + *

Overview

+ *

+ * This builder enables the creation of both synchronous and asynchronous clients for Azure AI Search Knowledge Agents, + * allowing you to interact with knowledge retrieval and agent-based search capabilities. The builder supports configuration + * of authentication, endpoint, agent name, API version, and HTTP pipeline options, following Azure SDK for Java standards. + *

+ * + *

Getting Started

+ *

+ * To create a client, configure the required properties such as the service endpoint, agent name, API version, and authentication + * credentials. The builder supports both API key and Microsoft Entra ID (role-based) authentication. Additional options such as + * custom HTTP pipeline policies, retry options, logging, and serialization can also be configured. + *

+ * + *

Authentication

+ *

+ * Azure AI Search Knowledge Agents support authentication using either an {@link AzureKeyCredential} (API key) or a + * {@link TokenCredential} (Microsoft Entra ID). When using Microsoft Entra ID, you may also specify a {@link SearchAudience} + * to target a specific Azure cloud environment. + *

+ * + *

Client Instantiation

+ *

+ * Use {@link #buildClient()} to create a synchronous {@link SearchKnowledgeAgentClient}, or {@link #buildAsyncClient()} to create + * an asynchronous {@link SearchKnowledgeAgentAsyncClient}. Each call to these methods returns a new client instance with the + * configured options. + *

+ * + *

Thread Safety

+ *

+ * Client instances created by this builder are thread-safe and intended to be shared and reused across threads. The builder itself + * is not thread-safe and should not be used concurrently from multiple threads. + *

+ * + *

Additional Information

+ *
    + *
  • For more information about Azure AI Search Knowledge Agents, see the Azure documentation.
  • + *
  • For authentication details, see the Azure AI Search security documentation.
  • + *
  • For Azure SDK for Java guidelines, see the Azure SDK for Java Introduction.
  • + *
+ * + * @see SearchKnowledgeAgentClient + * @see SearchKnowledgeAgentAsyncClient + * @see com.azure.search.documents.agents + */ +@ServiceClientBuilder(serviceClients = { SearchKnowledgeAgentClient.class, SearchKnowledgeAgentAsyncClient.class }) +public final class SearchKnowledgeAgentClientBuilder + implements AzureKeyCredentialTrait, + ConfigurationTrait, EndpointTrait, + HttpTrait, TokenCredentialTrait { + + private static final ClientLogger LOGGER = new ClientLogger(SearchKnowledgeAgentClientBuilder.class); + + private final List perCallPolicies = new ArrayList<>(); + private final List perRetryPolicies = new ArrayList<>(); + + private AzureKeyCredential azureKeyCredential; + private TokenCredential tokenCredential; + private SearchAudience audience; + private String endpoint; + private String agentName; + private SearchServiceVersion serviceVersion; + private HttpClient httpClient; + private HttpPipeline httpPipeline; + private HttpLogOptions httpLogOptions; + private ClientOptions clientOptions; + private Configuration configuration; + private RetryPolicy retryPolicy; + private RetryOptions retryOptions; + private JsonSerializer jsonSerializer; + + /** + * Creates a new builder instance. + */ + public SearchKnowledgeAgentClientBuilder() { + } + + /** + * Sets the service endpoint for the Azure AI Search instance. + * + * @param endpoint The URL of the Azure AI Search instance. + * @return The updated builder object. + */ + @Override + public SearchKnowledgeAgentClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /** + * Sets the agent name for the Azure AI Search agent. + * + * @param agentName The name of the agent. + * @return The updated builder object. + */ + public SearchKnowledgeAgentClientBuilder agentName(String agentName) { + this.agentName = agentName; + return this; + } + + /** + * Sets the API version to use for requests. + * + * @param apiVersion The API version. + * @return The updated builder object. + */ + public SearchKnowledgeAgentClientBuilder serviceVersion(SearchServiceVersion apiVersion) { + this.serviceVersion = apiVersion; + return this; + } + + @Override + public SearchKnowledgeAgentClientBuilder credential(AzureKeyCredential credential) { + this.azureKeyCredential = credential; + return this; + } + + @Override + public SearchKnowledgeAgentClientBuilder credential(TokenCredential credential) { + this.tokenCredential = credential; + return this; + } + + /** + * Sets the audience for the Azure AI Search instance. + * + * @param audience The audience to use. + * @return The updated builder object. + */ + public SearchKnowledgeAgentClientBuilder audience(SearchAudience audience) { + this.audience = audience; + return this; + } + + @Override + public SearchKnowledgeAgentClientBuilder httpLogOptions(HttpLogOptions logOptions) { + this.httpLogOptions = logOptions; + return this; + } + + @Override + public SearchKnowledgeAgentClientBuilder clientOptions(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + return this; + } + + @Override + public SearchKnowledgeAgentClientBuilder addPolicy(HttpPipelinePolicy policy) { + Objects.requireNonNull(policy, "'policy' cannot be null."); + this.perCallPolicies.add(policy); // For simplicity, treat as per-call; refine as needed + return this; + } + + @Override + public SearchKnowledgeAgentClientBuilder httpClient(HttpClient client) { + this.httpClient = client; + return this; + } + + @Override + public SearchKnowledgeAgentClientBuilder pipeline(HttpPipeline httpPipeline) { + this.httpPipeline = httpPipeline; + return this; + } + + @Override + public SearchKnowledgeAgentClientBuilder configuration(Configuration configuration) { + this.configuration = configuration; + return this; + } + + @Override + public SearchKnowledgeAgentClientBuilder retryOptions(RetryOptions retryOptions) { + this.retryOptions = retryOptions; + return this; + } + + /** + * Builds a synchronous {@link SearchKnowledgeAgentClient}. + * + * @return a new {@link SearchKnowledgeAgentClient} instance. + */ + public SearchKnowledgeAgentClient buildClient() { + validateRequiredFields(); + SearchServiceVersion serviceVersion + = this.serviceVersion != null ? this.serviceVersion : SearchServiceVersion.getLatest(); + HttpPipeline pipeline = this.httpPipeline != null + ? this.httpPipeline + : Utility.buildHttpPipeline(clientOptions, httpLogOptions, configuration, retryPolicy, retryOptions, + azureKeyCredential, tokenCredential, audience, perCallPolicies, perRetryPolicies, httpClient, LOGGER); + return new SearchKnowledgeAgentClient(endpoint, agentName, serviceVersion, pipeline); + } + + /** + * Builds an asynchronous {@link SearchKnowledgeAgentAsyncClient}. + * + * @return a new {@link SearchKnowledgeAgentAsyncClient} instance. + */ + public SearchKnowledgeAgentAsyncClient buildAsyncClient() { + validateRequiredFields(); + SearchServiceVersion serviceVersion + = this.serviceVersion != null ? this.serviceVersion : SearchServiceVersion.getLatest(); + HttpPipeline pipeline = this.httpPipeline != null + ? this.httpPipeline + : Utility.buildHttpPipeline(clientOptions, httpLogOptions, configuration, retryPolicy, retryOptions, + azureKeyCredential, tokenCredential, audience, perCallPolicies, perRetryPolicies, httpClient, LOGGER); + return new SearchKnowledgeAgentAsyncClient(endpoint, agentName, serviceVersion, pipeline); + } + + private void validateRequiredFields() { + Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); + Objects.requireNonNull(agentName, "'agentName' cannot be null."); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/KnowledgeAgentRetrievalClientImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/KnowledgeAgentRetrievalClientImpl.java new file mode 100644 index 000000000000..097dc2887b44 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/KnowledgeAgentRetrievalClientImpl.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.implementation; + +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 KnowledgeAgentRetrievalClient type. + */ +public final class KnowledgeAgentRetrievalClientImpl { + /** + * The endpoint URL of the search service. + */ + private final String endpoint; + + /** + * Gets The endpoint URL of the search service. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * The name of the agent. + */ + private final String agentName; + + /** + * Gets The name of the agent. + * + * @return the agentName value. + */ + public String getAgentName() { + return this.agentName; + } + + /** + * Api Version. + */ + private final String apiVersion; + + /** + * Gets Api Version. + * + * @return the apiVersion value. + */ + public String getApiVersion() { + return this.apiVersion; + } + + /** + * 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 KnowledgeRetrievalsImpl object to access its operations. + */ + private final KnowledgeRetrievalsImpl knowledgeRetrievals; + + /** + * Gets the KnowledgeRetrievalsImpl object to access its operations. + * + * @return the KnowledgeRetrievalsImpl object. + */ + public KnowledgeRetrievalsImpl getKnowledgeRetrievals() { + return this.knowledgeRetrievals; + } + + /** + * Initializes an instance of KnowledgeAgentRetrievalClient client. + * + * @param endpoint The endpoint URL of the search service. + * @param agentName The name of the agent. + * @param apiVersion Api Version. + */ + public KnowledgeAgentRetrievalClientImpl(String endpoint, String agentName, String apiVersion) { + this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), + JacksonAdapter.createDefaultSerializerAdapter(), endpoint, agentName, apiVersion); + } + + /** + * Initializes an instance of KnowledgeAgentRetrievalClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param endpoint The endpoint URL of the search service. + * @param agentName The name of the agent. + * @param apiVersion Api Version. + */ + public KnowledgeAgentRetrievalClientImpl(HttpPipeline httpPipeline, String endpoint, String agentName, + String apiVersion) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, agentName, apiVersion); + } + + /** + * Initializes an instance of KnowledgeAgentRetrievalClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param serializerAdapter The serializer to serialize an object into a string. + * @param endpoint The endpoint URL of the search service. + * @param agentName The name of the agent. + * @param apiVersion Api Version. + */ + public KnowledgeAgentRetrievalClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, + String endpoint, String agentName, String apiVersion) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.endpoint = endpoint; + this.agentName = agentName; + this.apiVersion = apiVersion; + this.knowledgeRetrievals = new KnowledgeRetrievalsImpl(this); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/KnowledgeRetrievalsImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/KnowledgeRetrievalsImpl.java new file mode 100644 index 000000000000..725b4767fdc2 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/KnowledgeRetrievalsImpl.java @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +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.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.agents.implementation.models.ErrorResponseException; +import com.azure.search.documents.agents.implementation.models.RequestOptions; +import com.azure.search.documents.agents.models.KnowledgeAgentRetrievalRequest; +import com.azure.search.documents.agents.models.KnowledgeAgentRetrievalResponse; +import java.util.UUID; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in KnowledgeRetrievals. + */ +public final class KnowledgeRetrievalsImpl { + /** + * The proxy service used to perform REST calls. + */ + private final KnowledgeRetrievalsService service; + + /** + * The service client containing this operation class. + */ + private final KnowledgeAgentRetrievalClientImpl client; + + /** + * Initializes an instance of KnowledgeRetrievalsImpl. + * + * @param client the instance of the service client containing this operation class. + */ + KnowledgeRetrievalsImpl(KnowledgeAgentRetrievalClientImpl client) { + this.service = RestProxy.create(KnowledgeRetrievalsService.class, client.getHttpPipeline(), + client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for KnowledgeAgentRetrievalClientKnowledgeRetrievals to be used by the + * proxy service to perform REST calls. + */ + @Host("{endpoint}/agents('{agentName}')") + @ServiceInterface(name = "KnowledgeAgentRetrie") + public interface KnowledgeRetrievalsService { + @Post("/retrieve") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Mono> retrieve(@HostParam("endpoint") String endpoint, + @HostParam("agentName") String agentName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @QueryParam("api-version") String apiVersion, + @HeaderParam("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, + @HeaderParam("Accept") String accept, + @BodyParam("application/json") KnowledgeAgentRetrievalRequest retrievalRequest, Context context); + + @Post("/retrieve") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Response retrieveSync(@HostParam("endpoint") String endpoint, + @HostParam("agentName") String agentName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @QueryParam("api-version") String apiVersion, + @HeaderParam("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, + @HeaderParam("Accept") String accept, + @BodyParam("application/json") KnowledgeAgentRetrievalRequest retrievalRequest, Context context); + } + + /** + * KnowledgeAgent retrieves relevant data from backing stores. + * + * @param retrievalRequest The retrieval request to process. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the output contract for the retrieval response along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> retrieveWithResponseAsync( + KnowledgeAgentRetrievalRequest retrievalRequest, String xMsQuerySourceAuthorization, + RequestOptions requestOptions) { + return FluxUtil.withContext(context -> retrieveWithResponseAsync(retrievalRequest, xMsQuerySourceAuthorization, + requestOptions, context)); + } + + /** + * KnowledgeAgent retrieves relevant data from backing stores. + * + * @param retrievalRequest The retrieval request to process. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the output contract for the retrieval response along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> retrieveWithResponseAsync( + KnowledgeAgentRetrievalRequest retrievalRequest, String xMsQuerySourceAuthorization, + RequestOptions requestOptions, Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.retrieve(this.client.getEndpoint(), this.client.getAgentName(), xMsClientRequestId, + this.client.getApiVersion(), xMsQuerySourceAuthorization, accept, retrievalRequest, context); + } + + /** + * KnowledgeAgent retrieves relevant data from backing stores. + * + * @param retrievalRequest The retrieval request to process. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the output contract for the retrieval response on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono retrieveAsync(KnowledgeAgentRetrievalRequest retrievalRequest, + String xMsQuerySourceAuthorization, RequestOptions requestOptions) { + return retrieveWithResponseAsync(retrievalRequest, xMsQuerySourceAuthorization, requestOptions) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * KnowledgeAgent retrieves relevant data from backing stores. + * + * @param retrievalRequest The retrieval request to process. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the output contract for the retrieval response on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono retrieveAsync(KnowledgeAgentRetrievalRequest retrievalRequest, + String xMsQuerySourceAuthorization, RequestOptions requestOptions, Context context) { + return retrieveWithResponseAsync(retrievalRequest, xMsQuerySourceAuthorization, requestOptions, context) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * KnowledgeAgent retrieves relevant data from backing stores. + * + * @param retrievalRequest The retrieval request to process. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the output contract for the retrieval response along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response retrieveWithResponse( + KnowledgeAgentRetrievalRequest retrievalRequest, String xMsQuerySourceAuthorization, + RequestOptions requestOptions, Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.retrieveSync(this.client.getEndpoint(), this.client.getAgentName(), xMsClientRequestId, + this.client.getApiVersion(), xMsQuerySourceAuthorization, accept, retrievalRequest, context); + } + + /** + * KnowledgeAgent retrieves relevant data from backing stores. + * + * @param retrievalRequest The retrieval request to process. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the output contract for the retrieval response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeAgentRetrievalResponse retrieve(KnowledgeAgentRetrievalRequest retrievalRequest, + String xMsQuerySourceAuthorization, RequestOptions requestOptions) { + return retrieveWithResponse(retrievalRequest, xMsQuerySourceAuthorization, requestOptions, Context.NONE) + .getValue(); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorAdditionalInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorAdditionalInfo.java new file mode 100644 index 000000000000..60a58fa045d4 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorAdditionalInfo.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.implementation.models; + +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; + +/** + * The resource management error additional info. + */ +@Immutable +public final class ErrorAdditionalInfo implements JsonSerializable { + /* + * The additional info type. + */ + private String type; + + /* + * The additional info. + */ + private Object info; + + /** + * Creates an instance of ErrorAdditionalInfo class. + */ + public ErrorAdditionalInfo() { + } + + /** + * Get the type property: The additional info type. + * + * @return the type value. + */ + public String getType() { + return this.type; + } + + /** + * Get the info property: The additional info. + * + * @return the info value. + */ + public Object getInfo() { + return this.info; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ErrorAdditionalInfo from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ErrorAdditionalInfo 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 ErrorAdditionalInfo. + */ + public static ErrorAdditionalInfo fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ErrorAdditionalInfo deserializedErrorAdditionalInfo = new ErrorAdditionalInfo(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedErrorAdditionalInfo.type = reader.getString(); + } else if ("info".equals(fieldName)) { + deserializedErrorAdditionalInfo.info = reader.readUntyped(); + } else { + reader.skipChildren(); + } + } + + return deserializedErrorAdditionalInfo; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorDetail.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorDetail.java new file mode 100644 index 000000000000..231a9229d38c --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorDetail.java @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.implementation.models; + +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; + +/** + * The error detail. + */ +@Immutable +public final class ErrorDetail implements JsonSerializable { + /* + * The error code. + */ + private String code; + + /* + * The error message. + */ + private String message; + + /* + * The error target. + */ + private String target; + + /* + * The error details. + */ + private List details; + + /* + * The error additional info. + */ + private List additionalInfo; + + /** + * Creates an instance of ErrorDetail class. + */ + public ErrorDetail() { + } + + /** + * Get the code property: The error code. + * + * @return the code value. + */ + public String getCode() { + return this.code; + } + + /** + * Get the message property: The error message. + * + * @return the message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Get the target property: The error target. + * + * @return the target value. + */ + public String getTarget() { + return this.target; + } + + /** + * Get the details property: The error details. + * + * @return the details value. + */ + public List getDetails() { + return this.details; + } + + /** + * Get the additionalInfo property: The error additional info. + * + * @return the additionalInfo value. + */ + public List getAdditionalInfo() { + return this.additionalInfo; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ErrorDetail from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ErrorDetail 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 ErrorDetail. + */ + public static ErrorDetail fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ErrorDetail deserializedErrorDetail = new ErrorDetail(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("code".equals(fieldName)) { + deserializedErrorDetail.code = reader.getString(); + } else if ("message".equals(fieldName)) { + deserializedErrorDetail.message = reader.getString(); + } else if ("target".equals(fieldName)) { + deserializedErrorDetail.target = reader.getString(); + } else if ("details".equals(fieldName)) { + List details = reader.readArray(reader1 -> ErrorDetail.fromJson(reader1)); + deserializedErrorDetail.details = details; + } else if ("additionalInfo".equals(fieldName)) { + List additionalInfo + = reader.readArray(reader1 -> ErrorAdditionalInfo.fromJson(reader1)); + deserializedErrorDetail.additionalInfo = additionalInfo; + } else { + reader.skipChildren(); + } + } + + return deserializedErrorDetail; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorResponse.java new file mode 100644 index 000000000000..8a511d8902b7 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorResponse.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Error response + * + * Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also + * follows the OData error response format.). + */ +@Fluent +public final class ErrorResponse implements JsonSerializable { + /* + * The error object. + */ + private ErrorDetail error; + + /** + * Creates an instance of ErrorResponse class. + */ + public ErrorResponse() { + } + + /** + * Get the error property: The error object. + * + * @return the error value. + */ + public ErrorDetail getError() { + return this.error; + } + + /** + * Set the error property: The error object. + * + * @param error the error value to set. + * @return the ErrorResponse object itself. + */ + public ErrorResponse setError(ErrorDetail error) { + this.error = error; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("error", this.error); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ErrorResponse from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ErrorResponse 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 ErrorResponse. + */ + public static ErrorResponse fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ErrorResponse deserializedErrorResponse = new ErrorResponse(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("error".equals(fieldName)) { + deserializedErrorResponse.error = ErrorDetail.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedErrorResponse; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorResponseException.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorResponseException.java new file mode 100644 index 000000000000..ce740f20c827 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/ErrorResponseException.java @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.implementation.models; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.HttpResponse; + +/** + * Exception thrown for an invalid response with ErrorResponse information. + */ +public final class ErrorResponseException extends HttpResponseException { + /** + * Initializes a new instance of the ErrorResponseException class. + * + * @param message the exception message or the response content if a message is not available. + * @param response the HTTP response. + */ + public ErrorResponseException(String message, HttpResponse response) { + super(message, response); + } + + /** + * Initializes a new instance of the ErrorResponseException class. + * + * @param message the exception message or the response content if a message is not available. + * @param response the HTTP response. + * @param value the deserialized response value. + */ + public ErrorResponseException(String message, HttpResponse response, ErrorResponse value) { + super(message, response, value); + } + + /** + * {@inheritDoc} + */ + @Override + public ErrorResponse getValue() { + return (ErrorResponse) super.getValue(); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/RequestOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/RequestOptions.java new file mode 100644 index 000000000000..bd0bf7e64432 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/RequestOptions.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.implementation.models; + +import com.azure.core.annotation.Fluent; +import java.util.UUID; + +/** + * Parameter group. + */ +@Fluent +public final class RequestOptions { + /* + * The tracking ID sent with the request to help with debugging. + */ + private UUID xMsClientRequestId; + + /** + * Creates an instance of RequestOptions class. + */ + public RequestOptions() { + } + + /** + * Get the xMsClientRequestId property: The tracking ID sent with the request to help with debugging. + * + * @return the xMsClientRequestId value. + */ + public UUID getXMsClientRequestId() { + return this.xMsClientRequestId; + } + + /** + * Set the xMsClientRequestId property: The tracking ID sent with the request to help with debugging. + * + * @param xMsClientRequestId the xMsClientRequestId value to set. + * @return the RequestOptions object itself. + */ + public RequestOptions setXMsClientRequestId(UUID xMsClientRequestId) { + this.xMsClientRequestId = xMsClientRequestId; + return this; + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/package-info.java new file mode 100644 index 000000000000..4556c569da0d --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/models/package-info.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +/** + * Package containing the data models for KnowledgeAgentRetrievalClient. + * Client that can be used to query an agent. + */ +package com.azure.search.documents.agents.implementation.models; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/package-info.java new file mode 100644 index 000000000000..5acb5a792275 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/implementation/package-info.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +/** + * Package containing the implementations for KnowledgeAgentRetrievalClient. + * Client that can be used to query an agent. + */ +package com.azure.search.documents.agents.implementation; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentActivityRecord.java new file mode 100644 index 000000000000..98114e2ecb8a --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentActivityRecord.java @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +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; + +/** + * Base type for activity records. + */ +@Immutable +public class KnowledgeAgentActivityRecord implements JsonSerializable { + /* + * The type of the activity record. + */ + private String type = "KnowledgeAgentActivityRecord"; + + /* + * The ID of the activity record. + */ + private final int id; + + /** + * Creates an instance of KnowledgeAgentActivityRecord class. + * + * @param id the id value to set. + */ + public KnowledgeAgentActivityRecord(int id) { + this.id = id; + } + + /** + * Get the type property: The type of the activity record. + * + * @return the type value. + */ + public String getType() { + return this.type; + } + + /** + * Get the id property: The ID of the activity record. + * + * @return the id value. + */ + public int getId() { + return this.id; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("id", this.id); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentActivityRecord from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentActivityRecord 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 KnowledgeAgentActivityRecord. + */ + public static KnowledgeAgentActivityRecord fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + readerToUse.nextToken(); // Prepare for reading + 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 ("AzureSearchQuery".equals(discriminatorValue)) { + return KnowledgeAgentSearchActivityRecord.fromJson(readerToUse.reset()); + } else if ("ModelQueryPlanning".equals(discriminatorValue)) { + return KnowledgeAgentModelQueryPlanningActivityRecord.fromJson(readerToUse.reset()); + } else if ("AzureSearchSemanticRanker".equals(discriminatorValue)) { + return KnowledgeAgentSemanticRankerActivityRecord.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + static KnowledgeAgentActivityRecord fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean idFound = false; + int id = 0; + String type = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getInt(); + idFound = true; + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + if (idFound) { + KnowledgeAgentActivityRecord deserializedKnowledgeAgentActivityRecord + = new KnowledgeAgentActivityRecord(id); + deserializedKnowledgeAgentActivityRecord.type = type; + + return deserializedKnowledgeAgentActivityRecord; + } + throw new IllegalStateException("Missing required property: id"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentAzureSearchDocReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentAzureSearchDocReference.java new file mode 100644 index 000000000000..f754eb866069 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentAzureSearchDocReference.java @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Represents an Azure Search document reference. + */ +@Fluent +public final class KnowledgeAgentAzureSearchDocReference extends KnowledgeAgentReference { + /* + * The type of the reference. + */ + private String type = "AzureSearchDoc"; + + /* + * The document key for the reference. + */ + private String docKey; + + /* + * Dictionary of + */ + private Map sourceData; + + /** + * Creates an instance of KnowledgeAgentAzureSearchDocReference class. + * + * @param id the id value to set. + * @param activitySource the activitySource value to set. + */ + public KnowledgeAgentAzureSearchDocReference(String id, int activitySource) { + super(id, activitySource); + } + + /** + * Get the type property: The type of the reference. + * + * @return the type value. + */ + @Override + public String getType() { + return this.type; + } + + /** + * Get the docKey property: The document key for the reference. + * + * @return the docKey value. + */ + public String getDocKey() { + return this.docKey; + } + + /** + * Set the docKey property: The document key for the reference. + * + * @param docKey the docKey value to set. + * @return the KnowledgeAgentAzureSearchDocReference object itself. + */ + public KnowledgeAgentAzureSearchDocReference setDocKey(String docKey) { + this.docKey = docKey; + return this; + } + + /** + * Get the sourceData property: Dictionary of <any>. + * + * @return the sourceData value. + */ + public Map getSourceData() { + return this.sourceData; + } + + /** + * Set the sourceData property: Dictionary of <any>. + * + * @param sourceData the sourceData value to set. + * @return the KnowledgeAgentAzureSearchDocReference object itself. + */ + public KnowledgeAgentAzureSearchDocReference setSourceData(Map sourceData) { + this.sourceData = sourceData; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", getId()); + jsonWriter.writeIntField("activitySource", getActivitySource()); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("docKey", this.docKey); + jsonWriter.writeMapField("sourceData", this.sourceData, (writer, element) -> writer.writeUntyped(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentAzureSearchDocReference from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentAzureSearchDocReference 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 KnowledgeAgentAzureSearchDocReference. + */ + public static KnowledgeAgentAzureSearchDocReference fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean idFound = false; + String id = null; + boolean activitySourceFound = false; + int activitySource = 0; + String type = "AzureSearchDoc"; + String docKey = null; + Map sourceData = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + idFound = true; + } else if ("activitySource".equals(fieldName)) { + activitySource = reader.getInt(); + activitySourceFound = true; + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("docKey".equals(fieldName)) { + docKey = reader.getString(); + } else if ("sourceData".equals(fieldName)) { + sourceData = reader.readMap(reader1 -> reader1.readUntyped()); + } else { + reader.skipChildren(); + } + } + if (idFound && activitySourceFound) { + KnowledgeAgentAzureSearchDocReference deserializedKnowledgeAgentAzureSearchDocReference + = new KnowledgeAgentAzureSearchDocReference(id, activitySource); + deserializedKnowledgeAgentAzureSearchDocReference.type = type; + deserializedKnowledgeAgentAzureSearchDocReference.docKey = docKey; + deserializedKnowledgeAgentAzureSearchDocReference.sourceData = sourceData; + + return deserializedKnowledgeAgentAzureSearchDocReference; + } + List missingProperties = new ArrayList<>(); + if (!idFound) { + missingProperties.add("id"); + } + if (!activitySourceFound) { + missingProperties.add("activitySource"); + } + + throw new IllegalStateException( + "Missing required property/properties: " + String.join(", ", missingProperties)); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentIndexParams.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentIndexParams.java new file mode 100644 index 000000000000..ab5daf17ced9 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentIndexParams.java @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +import com.azure.core.annotation.Fluent; +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 KnowledgeAgentIndexParams model. + */ +@Fluent +public final class KnowledgeAgentIndexParams implements JsonSerializable { + /* + * The name of the index the params apply to. + */ + private String indexName; + + /* + * A filter condition applied to the index (e.g., 'State eq VA'). + */ + private String filterAddOn; + + /* + * Limits the number of documents considered for ranking. + */ + private Integer maxDocsForReranker; + + /* + * A threshold for reranking results (range: 0-4). + */ + private Float rerankerThreshold; + + /* + * Indicates whether reference source data should be included. + */ + private Boolean includeReferenceSourceData; + + /** + * Creates an instance of KnowledgeAgentIndexParams class. + */ + public KnowledgeAgentIndexParams() { + } + + /** + * Get the indexName property: The name of the index the params apply to. + * + * @return the indexName value. + */ + public String getIndexName() { + return this.indexName; + } + + /** + * Set the indexName property: The name of the index the params apply to. + * + * @param indexName the indexName value to set. + * @return the KnowledgeAgentIndexParams object itself. + */ + public KnowledgeAgentIndexParams setIndexName(String indexName) { + this.indexName = indexName; + return this; + } + + /** + * Get the filterAddOn property: A filter condition applied to the index (e.g., 'State eq VA'). + * + * @return the filterAddOn value. + */ + public String getFilterAddOn() { + return this.filterAddOn; + } + + /** + * Set the filterAddOn property: A filter condition applied to the index (e.g., 'State eq VA'). + * + * @param filterAddOn the filterAddOn value to set. + * @return the KnowledgeAgentIndexParams object itself. + */ + public KnowledgeAgentIndexParams setFilterAddOn(String filterAddOn) { + this.filterAddOn = filterAddOn; + return this; + } + + /** + * Get the maxDocsForReranker property: Limits the number of documents considered for ranking. + * + * @return the maxDocsForReranker value. + */ + public Integer getMaxDocsForReranker() { + return this.maxDocsForReranker; + } + + /** + * Set the maxDocsForReranker property: Limits the number of documents considered for ranking. + * + * @param maxDocsForReranker the maxDocsForReranker value to set. + * @return the KnowledgeAgentIndexParams object itself. + */ + public KnowledgeAgentIndexParams setMaxDocsForReranker(Integer maxDocsForReranker) { + this.maxDocsForReranker = maxDocsForReranker; + return this; + } + + /** + * Get the rerankerThreshold property: A threshold for reranking results (range: 0-4). + * + * @return the rerankerThreshold value. + */ + public Float getRerankerThreshold() { + return this.rerankerThreshold; + } + + /** + * Set the rerankerThreshold property: A threshold for reranking results (range: 0-4). + * + * @param rerankerThreshold the rerankerThreshold value to set. + * @return the KnowledgeAgentIndexParams object itself. + */ + public KnowledgeAgentIndexParams setRerankerThreshold(Float rerankerThreshold) { + this.rerankerThreshold = rerankerThreshold; + return this; + } + + /** + * Get the includeReferenceSourceData property: Indicates whether reference source data should be included. + * + * @return the includeReferenceSourceData value. + */ + public Boolean isIncludeReferenceSourceData() { + return this.includeReferenceSourceData; + } + + /** + * Set the includeReferenceSourceData property: Indicates whether reference source data should be included. + * + * @param includeReferenceSourceData the includeReferenceSourceData value to set. + * @return the KnowledgeAgentIndexParams object itself. + */ + public KnowledgeAgentIndexParams setIncludeReferenceSourceData(Boolean includeReferenceSourceData) { + this.includeReferenceSourceData = includeReferenceSourceData; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("indexName", this.indexName); + jsonWriter.writeStringField("filterAddOn", this.filterAddOn); + jsonWriter.writeNumberField("maxDocsForReranker", this.maxDocsForReranker); + jsonWriter.writeNumberField("rerankerThreshold", this.rerankerThreshold); + jsonWriter.writeBooleanField("includeReferenceSourceData", this.includeReferenceSourceData); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentIndexParams from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentIndexParams 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 KnowledgeAgentIndexParams. + */ + public static KnowledgeAgentIndexParams fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + KnowledgeAgentIndexParams deserializedKnowledgeAgentIndexParams = new KnowledgeAgentIndexParams(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("indexName".equals(fieldName)) { + deserializedKnowledgeAgentIndexParams.indexName = reader.getString(); + } else if ("filterAddOn".equals(fieldName)) { + deserializedKnowledgeAgentIndexParams.filterAddOn = reader.getString(); + } else if ("maxDocsForReranker".equals(fieldName)) { + deserializedKnowledgeAgentIndexParams.maxDocsForReranker = reader.getNullable(JsonReader::getInt); + } else if ("rerankerThreshold".equals(fieldName)) { + deserializedKnowledgeAgentIndexParams.rerankerThreshold = reader.getNullable(JsonReader::getFloat); + } else if ("includeReferenceSourceData".equals(fieldName)) { + deserializedKnowledgeAgentIndexParams.includeReferenceSourceData + = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + + return deserializedKnowledgeAgentIndexParams; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessage.java new file mode 100644 index 000000000000..7a72fb64a795 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessage.java @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +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.ArrayList; +import java.util.List; + +/** + * The natural language message style object. + */ +@Immutable +public final class KnowledgeAgentMessage implements JsonSerializable { + /* + * The role of the tool response. + */ + private final String role; + + /* + * The content property. + */ + private final List content; + + /** + * Creates an instance of KnowledgeAgentMessage class. + * + * @param role the role value to set. + * @param content the content value to set. + */ + public KnowledgeAgentMessage(String role, List content) { + this.role = role; + this.content = content; + } + + /** + * Get the role property: The role of the tool response. + * + * @return the role value. + */ + public String getRole() { + return this.role; + } + + /** + * Get the content property: The content property. + * + * @return the content value. + */ + public List getContent() { + return this.content; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("role", this.role); + jsonWriter.writeArrayField("content", this.content, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentMessage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentMessage 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 KnowledgeAgentMessage. + */ + public static KnowledgeAgentMessage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean roleFound = false; + String role = null; + boolean contentFound = false; + List content = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("role".equals(fieldName)) { + role = reader.getString(); + roleFound = true; + } else if ("content".equals(fieldName)) { + content = reader.readArray(reader1 -> KnowledgeAgentMessageContent.fromJson(reader1)); + contentFound = true; + } else { + reader.skipChildren(); + } + } + if (roleFound && contentFound) { + return new KnowledgeAgentMessage(role, content); + } + List missingProperties = new ArrayList<>(); + if (!roleFound) { + missingProperties.add("role"); + } + if (!contentFound) { + missingProperties.add("content"); + } + + throw new IllegalStateException( + "Missing required property/properties: " + String.join(", ", missingProperties)); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageContent.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageContent.java new file mode 100644 index 000000000000..d5c11ffd6b6a --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageContent.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +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; + +/** + * Specifies the type of the message content. + */ +@Immutable +public class KnowledgeAgentMessageContent implements JsonSerializable { + /* + * The type of the message + */ + private KnowledgeAgentMessageContentType type + = KnowledgeAgentMessageContentType.fromString("KnowledgeAgentMessageContent"); + + /** + * Creates an instance of KnowledgeAgentMessageContent class. + */ + public KnowledgeAgentMessageContent() { + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + public KnowledgeAgentMessageContentType getType() { + return this.type; + } + + /** + * {@inheritDoc} + */ + @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 KnowledgeAgentMessageContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentMessageContent 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 KnowledgeAgentMessageContent. + */ + public static KnowledgeAgentMessageContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + readerToUse.nextToken(); // Prepare for reading + 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 ("text".equals(discriminatorValue)) { + return KnowledgeAgentMessageTextContent.fromJson(readerToUse.reset()); + } else if ("image".equals(discriminatorValue)) { + return KnowledgeAgentMessageImageContent.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + static KnowledgeAgentMessageContent fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + KnowledgeAgentMessageContent deserializedKnowledgeAgentMessageContent = new KnowledgeAgentMessageContent(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedKnowledgeAgentMessageContent.type + = KnowledgeAgentMessageContentType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedKnowledgeAgentMessageContent; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageContentType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageContentType.java new file mode 100644 index 000000000000..e07379f3d695 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageContentType.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type of message content. + */ +public final class KnowledgeAgentMessageContentType extends ExpandableStringEnum { + /** + * Text message content kind. + */ + public static final KnowledgeAgentMessageContentType TEXT = fromString("text"); + + /** + * Image message content kind. + */ + public static final KnowledgeAgentMessageContentType IMAGE = fromString("image"); + + /** + * Creates a new instance of KnowledgeAgentMessageContentType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public KnowledgeAgentMessageContentType() { + } + + /** + * Creates or finds a KnowledgeAgentMessageContentType from its string representation. + * + * @param name a name to look for. + * @return the corresponding KnowledgeAgentMessageContentType. + */ + public static KnowledgeAgentMessageContentType fromString(String name) { + return fromString(name, KnowledgeAgentMessageContentType.class); + } + + /** + * Gets known KnowledgeAgentMessageContentType values. + * + * @return known KnowledgeAgentMessageContentType values. + */ + public static Collection values() { + return values(KnowledgeAgentMessageContentType.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageImageContent.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageImageContent.java new file mode 100644 index 000000000000..0a5cbbbe9575 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageImageContent.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +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; + +/** + * Text message type. + */ +@Immutable +public final class KnowledgeAgentMessageImageContent extends KnowledgeAgentMessageContent { + /* + * The type of the message + */ + private KnowledgeAgentMessageContentType type = KnowledgeAgentMessageContentType.IMAGE; + + /* + * The image property. + */ + private final KnowledgeAgentMessageImageContentImage image; + + /** + * Creates an instance of KnowledgeAgentMessageImageContent class. + * + * @param image the image value to set. + */ + public KnowledgeAgentMessageImageContent(KnowledgeAgentMessageImageContentImage image) { + this.image = image; + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + @Override + public KnowledgeAgentMessageContentType getType() { + return this.type; + } + + /** + * Get the image property: The image property. + * + * @return the image value. + */ + public KnowledgeAgentMessageImageContentImage getImage() { + return this.image; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("image", this.image); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentMessageImageContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentMessageImageContent 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 KnowledgeAgentMessageImageContent. + */ + public static KnowledgeAgentMessageImageContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean imageFound = false; + KnowledgeAgentMessageImageContentImage image = null; + KnowledgeAgentMessageContentType type = KnowledgeAgentMessageContentType.IMAGE; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("image".equals(fieldName)) { + image = KnowledgeAgentMessageImageContentImage.fromJson(reader); + imageFound = true; + } else if ("type".equals(fieldName)) { + type = KnowledgeAgentMessageContentType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + if (imageFound) { + KnowledgeAgentMessageImageContent deserializedKnowledgeAgentMessageImageContent + = new KnowledgeAgentMessageImageContent(image); + deserializedKnowledgeAgentMessageImageContent.type = type; + + return deserializedKnowledgeAgentMessageImageContent; + } + throw new IllegalStateException("Missing required property: image"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageImageContentImage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageImageContentImage.java new file mode 100644 index 000000000000..a613f55b76b3 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageImageContentImage.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +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; + +/** + * The KnowledgeAgentMessageImageContentImage model. + */ +@Immutable +public final class KnowledgeAgentMessageImageContentImage + implements JsonSerializable { + /* + * The url of the image. + */ + private final String url; + + /** + * Creates an instance of KnowledgeAgentMessageImageContentImage class. + * + * @param url the url value to set. + */ + public KnowledgeAgentMessageImageContentImage(String url) { + this.url = url; + } + + /** + * Get the url property: The url of the image. + * + * @return the url value. + */ + public String getUrl() { + return this.url; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("url", this.url); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentMessageImageContentImage from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentMessageImageContentImage 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 KnowledgeAgentMessageImageContentImage. + */ + public static KnowledgeAgentMessageImageContentImage fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean urlFound = false; + String url = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("url".equals(fieldName)) { + url = reader.getString(); + urlFound = true; + } else { + reader.skipChildren(); + } + } + if (urlFound) { + return new KnowledgeAgentMessageImageContentImage(url); + } + throw new IllegalStateException("Missing required property: url"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageTextContent.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageTextContent.java new file mode 100644 index 000000000000..a6f801dd7f38 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentMessageTextContent.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +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; + +/** + * Text message type. + */ +@Immutable +public final class KnowledgeAgentMessageTextContent extends KnowledgeAgentMessageContent { + /* + * The type of the message + */ + private KnowledgeAgentMessageContentType type = KnowledgeAgentMessageContentType.TEXT; + + /* + * The text property. + */ + private final String text; + + /** + * Creates an instance of KnowledgeAgentMessageTextContent class. + * + * @param text the text value to set. + */ + public KnowledgeAgentMessageTextContent(String text) { + this.text = text; + } + + /** + * Get the type property: The type of the message. + * + * @return the type value. + */ + @Override + public KnowledgeAgentMessageContentType getType() { + return this.type; + } + + /** + * Get the text property: The text property. + * + * @return the text value. + */ + public String getText() { + return this.text; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentMessageTextContent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentMessageTextContent 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 KnowledgeAgentMessageTextContent. + */ + public static KnowledgeAgentMessageTextContent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean textFound = false; + String text = null; + KnowledgeAgentMessageContentType type = KnowledgeAgentMessageContentType.TEXT; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("text".equals(fieldName)) { + text = reader.getString(); + textFound = true; + } else if ("type".equals(fieldName)) { + type = KnowledgeAgentMessageContentType.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + if (textFound) { + KnowledgeAgentMessageTextContent deserializedKnowledgeAgentMessageTextContent + = new KnowledgeAgentMessageTextContent(text); + deserializedKnowledgeAgentMessageTextContent.type = type; + + return deserializedKnowledgeAgentMessageTextContent; + } + throw new IllegalStateException("Missing required property: text"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentModelQueryPlanningActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentModelQueryPlanningActivityRecord.java new file mode 100644 index 000000000000..9c056e5798f0 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentModelQueryPlanningActivityRecord.java @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Represents an LLM query planning activity record. + */ +@Fluent +public final class KnowledgeAgentModelQueryPlanningActivityRecord extends KnowledgeAgentActivityRecord { + /* + * The type of the activity record. + */ + private String type = "ModelQueryPlanning"; + + /* + * The number of input tokens for the LLM query planning activity. + */ + private Integer inputTokens; + + /* + * The number of output tokens for the LLM query planning activity. + */ + private Integer outputTokens; + + /* + * The elapsed time in milliseconds for the model activity. + */ + private Integer elapsedMs; + + /** + * Creates an instance of KnowledgeAgentModelQueryPlanningActivityRecord class. + * + * @param id the id value to set. + */ + public KnowledgeAgentModelQueryPlanningActivityRecord(int id) { + super(id); + } + + /** + * Get the type property: The type of the activity record. + * + * @return the type value. + */ + @Override + public String getType() { + return this.type; + } + + /** + * Get the inputTokens property: The number of input tokens for the LLM query planning activity. + * + * @return the inputTokens value. + */ + public Integer getInputTokens() { + return this.inputTokens; + } + + /** + * Set the inputTokens property: The number of input tokens for the LLM query planning activity. + * + * @param inputTokens the inputTokens value to set. + * @return the KnowledgeAgentModelQueryPlanningActivityRecord object itself. + */ + public KnowledgeAgentModelQueryPlanningActivityRecord setInputTokens(Integer inputTokens) { + this.inputTokens = inputTokens; + return this; + } + + /** + * Get the outputTokens property: The number of output tokens for the LLM query planning activity. + * + * @return the outputTokens value. + */ + public Integer getOutputTokens() { + return this.outputTokens; + } + + /** + * Set the outputTokens property: The number of output tokens for the LLM query planning activity. + * + * @param outputTokens the outputTokens value to set. + * @return the KnowledgeAgentModelQueryPlanningActivityRecord object itself. + */ + public KnowledgeAgentModelQueryPlanningActivityRecord setOutputTokens(Integer outputTokens) { + this.outputTokens = outputTokens; + return this; + } + + /** + * Get the elapsedMs property: The elapsed time in milliseconds for the model activity. + * + * @return the elapsedMs value. + */ + public Integer getElapsedMs() { + return this.elapsedMs; + } + + /** + * Set the elapsedMs property: The elapsed time in milliseconds for the model activity. + * + * @param elapsedMs the elapsedMs value to set. + * @return the KnowledgeAgentModelQueryPlanningActivityRecord object itself. + */ + public KnowledgeAgentModelQueryPlanningActivityRecord setElapsedMs(Integer elapsedMs) { + this.elapsedMs = elapsedMs; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("id", getId()); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeNumberField("inputTokens", this.inputTokens); + jsonWriter.writeNumberField("outputTokens", this.outputTokens); + jsonWriter.writeNumberField("elapsedMs", this.elapsedMs); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentModelQueryPlanningActivityRecord from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentModelQueryPlanningActivityRecord 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 KnowledgeAgentModelQueryPlanningActivityRecord. + */ + public static KnowledgeAgentModelQueryPlanningActivityRecord fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean idFound = false; + int id = 0; + String type = "ModelQueryPlanning"; + Integer inputTokens = null; + Integer outputTokens = null; + Integer elapsedMs = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getInt(); + idFound = true; + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("inputTokens".equals(fieldName)) { + inputTokens = reader.getNullable(JsonReader::getInt); + } else if ("outputTokens".equals(fieldName)) { + outputTokens = reader.getNullable(JsonReader::getInt); + } else if ("elapsedMs".equals(fieldName)) { + elapsedMs = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + if (idFound) { + KnowledgeAgentModelQueryPlanningActivityRecord deserializedKnowledgeAgentModelQueryPlanningActivityRecord + = new KnowledgeAgentModelQueryPlanningActivityRecord(id); + deserializedKnowledgeAgentModelQueryPlanningActivityRecord.type = type; + deserializedKnowledgeAgentModelQueryPlanningActivityRecord.inputTokens = inputTokens; + deserializedKnowledgeAgentModelQueryPlanningActivityRecord.outputTokens = outputTokens; + deserializedKnowledgeAgentModelQueryPlanningActivityRecord.elapsedMs = elapsedMs; + + return deserializedKnowledgeAgentModelQueryPlanningActivityRecord; + } + throw new IllegalStateException("Missing required property: id"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentReference.java new file mode 100644 index 000000000000..3f5de9f3bef7 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentReference.java @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +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.ArrayList; +import java.util.List; + +/** + * Base type for references. + */ +@Immutable +public class KnowledgeAgentReference implements JsonSerializable { + /* + * The type of the reference. + */ + private String type = "KnowledgeAgentReference"; + + /* + * The ID of the reference. + */ + private final String id; + + /* + * The source activity ID for the reference. + */ + private final int activitySource; + + /** + * Creates an instance of KnowledgeAgentReference class. + * + * @param id the id value to set. + * @param activitySource the activitySource value to set. + */ + public KnowledgeAgentReference(String id, int activitySource) { + this.id = id; + this.activitySource = activitySource; + } + + /** + * Get the type property: The type of the reference. + * + * @return the type value. + */ + public String getType() { + return this.type; + } + + /** + * Get the id property: The ID of the reference. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Get the activitySource property: The source activity ID for the reference. + * + * @return the activitySource value. + */ + public int getActivitySource() { + return this.activitySource; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("id", this.id); + jsonWriter.writeIntField("activitySource", this.activitySource); + jsonWriter.writeStringField("type", this.type); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentReference from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentReference 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 KnowledgeAgentReference. + */ + public static KnowledgeAgentReference fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + readerToUse.nextToken(); // Prepare for reading + 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 ("AzureSearchDoc".equals(discriminatorValue)) { + return KnowledgeAgentAzureSearchDocReference.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + static KnowledgeAgentReference fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean idFound = false; + String id = null; + boolean activitySourceFound = false; + int activitySource = 0; + String type = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + idFound = true; + } else if ("activitySource".equals(fieldName)) { + activitySource = reader.getInt(); + activitySourceFound = true; + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else { + reader.skipChildren(); + } + } + if (idFound && activitySourceFound) { + KnowledgeAgentReference deserializedKnowledgeAgentReference + = new KnowledgeAgentReference(id, activitySource); + deserializedKnowledgeAgentReference.type = type; + + return deserializedKnowledgeAgentReference; + } + List missingProperties = new ArrayList<>(); + if (!idFound) { + missingProperties.add("id"); + } + if (!activitySourceFound) { + missingProperties.add("activitySource"); + } + + throw new IllegalStateException( + "Missing required property/properties: " + String.join(", ", missingProperties)); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentRetrievalRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentRetrievalRequest.java new file mode 100644 index 000000000000..87035328be76 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentRetrievalRequest.java @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +import com.azure.core.annotation.Fluent; +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; + +/** + * The input contract for the retrieval request. + */ +@Fluent +public final class KnowledgeAgentRetrievalRequest implements JsonSerializable { + /* + * The messages property. + */ + private final List messages; + + /* + * The targetIndexParams property. + */ + private List targetIndexParams; + + /** + * Creates an instance of KnowledgeAgentRetrievalRequest class. + * + * @param messages the messages value to set. + */ + public KnowledgeAgentRetrievalRequest(List messages) { + this.messages = messages; + } + + /** + * Get the messages property: The messages property. + * + * @return the messages value. + */ + public List getMessages() { + return this.messages; + } + + /** + * Get the targetIndexParams property: The targetIndexParams property. + * + * @return the targetIndexParams value. + */ + public List getTargetIndexParams() { + return this.targetIndexParams; + } + + /** + * Set the targetIndexParams property: The targetIndexParams property. + * + * @param targetIndexParams the targetIndexParams value to set. + * @return the KnowledgeAgentRetrievalRequest object itself. + */ + public KnowledgeAgentRetrievalRequest setTargetIndexParams(List targetIndexParams) { + this.targetIndexParams = targetIndexParams; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("messages", this.messages, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("targetIndexParams", this.targetIndexParams, + (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentRetrievalRequest from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentRetrievalRequest 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 KnowledgeAgentRetrievalRequest. + */ + public static KnowledgeAgentRetrievalRequest fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean messagesFound = false; + List messages = null; + List targetIndexParams = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("messages".equals(fieldName)) { + messages = reader.readArray(reader1 -> KnowledgeAgentMessage.fromJson(reader1)); + messagesFound = true; + } else if ("targetIndexParams".equals(fieldName)) { + targetIndexParams = reader.readArray(reader1 -> KnowledgeAgentIndexParams.fromJson(reader1)); + } else { + reader.skipChildren(); + } + } + if (messagesFound) { + KnowledgeAgentRetrievalRequest deserializedKnowledgeAgentRetrievalRequest + = new KnowledgeAgentRetrievalRequest(messages); + deserializedKnowledgeAgentRetrievalRequest.targetIndexParams = targetIndexParams; + + return deserializedKnowledgeAgentRetrievalRequest; + } + throw new IllegalStateException("Missing required property: messages"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentRetrievalResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentRetrievalResponse.java new file mode 100644 index 000000000000..3f9ba97cd6b3 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentRetrievalResponse.java @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +import com.azure.core.annotation.Fluent; +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; + +/** + * The output contract for the retrieval response. + */ +@Fluent +public final class KnowledgeAgentRetrievalResponse implements JsonSerializable { + /* + * The response property. + */ + private List response; + + /* + * The activity records for tracking progress and billing implications. + */ + private List activity; + + /* + * The references for the retrieval data used in the response. + */ + private List references; + + /** + * Creates an instance of KnowledgeAgentRetrievalResponse class. + */ + public KnowledgeAgentRetrievalResponse() { + } + + /** + * Get the response property: The response property. + * + * @return the response value. + */ + public List getResponse() { + return this.response; + } + + /** + * Set the response property: The response property. + * + * @param response the response value to set. + * @return the KnowledgeAgentRetrievalResponse object itself. + */ + public KnowledgeAgentRetrievalResponse setResponse(List response) { + this.response = response; + return this; + } + + /** + * Get the activity property: The activity records for tracking progress and billing implications. + * + * @return the activity value. + */ + public List getActivity() { + return this.activity; + } + + /** + * Set the activity property: The activity records for tracking progress and billing implications. + * + * @param activity the activity value to set. + * @return the KnowledgeAgentRetrievalResponse object itself. + */ + public KnowledgeAgentRetrievalResponse setActivity(List activity) { + this.activity = activity; + return this; + } + + /** + * Get the references property: The references for the retrieval data used in the response. + * + * @return the references value. + */ + public List getReferences() { + return this.references; + } + + /** + * Set the references property: The references for the retrieval data used in the response. + * + * @param references the references value to set. + * @return the KnowledgeAgentRetrievalResponse object itself. + */ + public KnowledgeAgentRetrievalResponse setReferences(List references) { + this.references = references; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("response", this.response, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("activity", this.activity, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("references", this.references, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentRetrievalResponse from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentRetrievalResponse 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 KnowledgeAgentRetrievalResponse. + */ + public static KnowledgeAgentRetrievalResponse fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + KnowledgeAgentRetrievalResponse deserializedKnowledgeAgentRetrievalResponse + = new KnowledgeAgentRetrievalResponse(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("response".equals(fieldName)) { + List response + = reader.readArray(reader1 -> KnowledgeAgentMessage.fromJson(reader1)); + deserializedKnowledgeAgentRetrievalResponse.response = response; + } else if ("activity".equals(fieldName)) { + List activity + = reader.readArray(reader1 -> KnowledgeAgentActivityRecord.fromJson(reader1)); + deserializedKnowledgeAgentRetrievalResponse.activity = activity; + } else if ("references".equals(fieldName)) { + List references + = reader.readArray(reader1 -> KnowledgeAgentReference.fromJson(reader1)); + deserializedKnowledgeAgentRetrievalResponse.references = references; + } else { + reader.skipChildren(); + } + } + + return deserializedKnowledgeAgentRetrievalResponse; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentSearchActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentSearchActivityRecord.java new file mode 100644 index 000000000000..19397913703c --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentSearchActivityRecord.java @@ -0,0 +1,247 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Represents a retrieval activity record. + */ +@Fluent +public final class KnowledgeAgentSearchActivityRecord extends KnowledgeAgentActivityRecord { + /* + * The type of the activity record. + */ + private String type = "AzureSearchQuery"; + + /* + * The target index for the retrieval activity. + */ + private String targetIndex; + + /* + * The query details for the retrieval activity. + */ + private KnowledgeAgentSearchActivityRecordQuery query; + + /* + * The query time for this retrieval activity. + */ + private OffsetDateTime queryTime; + + /* + * The count of documents retrieved. + */ + private Integer count; + + /* + * The elapsed time in milliseconds for the retrieval activity. + */ + private Integer elapsedMs; + + /** + * Creates an instance of KnowledgeAgentSearchActivityRecord class. + * + * @param id the id value to set. + */ + public KnowledgeAgentSearchActivityRecord(int id) { + super(id); + } + + /** + * Get the type property: The type of the activity record. + * + * @return the type value. + */ + @Override + public String getType() { + return this.type; + } + + /** + * Get the targetIndex property: The target index for the retrieval activity. + * + * @return the targetIndex value. + */ + public String getTargetIndex() { + return this.targetIndex; + } + + /** + * Set the targetIndex property: The target index for the retrieval activity. + * + * @param targetIndex the targetIndex value to set. + * @return the KnowledgeAgentSearchActivityRecord object itself. + */ + public KnowledgeAgentSearchActivityRecord setTargetIndex(String targetIndex) { + this.targetIndex = targetIndex; + return this; + } + + /** + * Get the query property: The query details for the retrieval activity. + * + * @return the query value. + */ + public KnowledgeAgentSearchActivityRecordQuery getQuery() { + return this.query; + } + + /** + * Set the query property: The query details for the retrieval activity. + * + * @param query the query value to set. + * @return the KnowledgeAgentSearchActivityRecord object itself. + */ + public KnowledgeAgentSearchActivityRecord setQuery(KnowledgeAgentSearchActivityRecordQuery query) { + this.query = query; + return this; + } + + /** + * Get the queryTime property: The query time for this retrieval activity. + * + * @return the queryTime value. + */ + public OffsetDateTime getQueryTime() { + return this.queryTime; + } + + /** + * Set the queryTime property: The query time for this retrieval activity. + * + * @param queryTime the queryTime value to set. + * @return the KnowledgeAgentSearchActivityRecord object itself. + */ + public KnowledgeAgentSearchActivityRecord setQueryTime(OffsetDateTime queryTime) { + this.queryTime = queryTime; + return this; + } + + /** + * Get the count property: The count of documents retrieved. + * + * @return the count value. + */ + public Integer getCount() { + return this.count; + } + + /** + * Set the count property: The count of documents retrieved. + * + * @param count the count value to set. + * @return the KnowledgeAgentSearchActivityRecord object itself. + */ + public KnowledgeAgentSearchActivityRecord setCount(Integer count) { + this.count = count; + return this; + } + + /** + * Get the elapsedMs property: The elapsed time in milliseconds for the retrieval activity. + * + * @return the elapsedMs value. + */ + public Integer getElapsedMs() { + return this.elapsedMs; + } + + /** + * Set the elapsedMs property: The elapsed time in milliseconds for the retrieval activity. + * + * @param elapsedMs the elapsedMs value to set. + * @return the KnowledgeAgentSearchActivityRecord object itself. + */ + public KnowledgeAgentSearchActivityRecord setElapsedMs(Integer elapsedMs) { + this.elapsedMs = elapsedMs; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("id", getId()); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("targetIndex", this.targetIndex); + jsonWriter.writeJsonField("query", this.query); + jsonWriter.writeStringField("queryTime", + this.queryTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.queryTime)); + jsonWriter.writeNumberField("count", this.count); + jsonWriter.writeNumberField("elapsedMs", this.elapsedMs); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentSearchActivityRecord from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentSearchActivityRecord 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 KnowledgeAgentSearchActivityRecord. + */ + public static KnowledgeAgentSearchActivityRecord fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean idFound = false; + int id = 0; + String type = "AzureSearchQuery"; + String targetIndex = null; + KnowledgeAgentSearchActivityRecordQuery query = null; + OffsetDateTime queryTime = null; + Integer count = null; + Integer elapsedMs = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getInt(); + idFound = true; + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("targetIndex".equals(fieldName)) { + targetIndex = reader.getString(); + } else if ("query".equals(fieldName)) { + query = KnowledgeAgentSearchActivityRecordQuery.fromJson(reader); + } else if ("queryTime".equals(fieldName)) { + queryTime = reader + .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); + } else if ("count".equals(fieldName)) { + count = reader.getNullable(JsonReader::getInt); + } else if ("elapsedMs".equals(fieldName)) { + elapsedMs = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + if (idFound) { + KnowledgeAgentSearchActivityRecord deserializedKnowledgeAgentSearchActivityRecord + = new KnowledgeAgentSearchActivityRecord(id); + deserializedKnowledgeAgentSearchActivityRecord.type = type; + deserializedKnowledgeAgentSearchActivityRecord.targetIndex = targetIndex; + deserializedKnowledgeAgentSearchActivityRecord.query = query; + deserializedKnowledgeAgentSearchActivityRecord.queryTime = queryTime; + deserializedKnowledgeAgentSearchActivityRecord.count = count; + deserializedKnowledgeAgentSearchActivityRecord.elapsedMs = elapsedMs; + + return deserializedKnowledgeAgentSearchActivityRecord; + } + throw new IllegalStateException("Missing required property: id"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentSearchActivityRecordQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentSearchActivityRecordQuery.java new file mode 100644 index 000000000000..09ddac847bd7 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentSearchActivityRecordQuery.java @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +import com.azure.core.annotation.Fluent; +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 query details for the retrieval activity. + */ +@Fluent +public final class KnowledgeAgentSearchActivityRecordQuery + implements JsonSerializable { + /* + * The search string. + */ + private String search; + + /* + * The filter string. + */ + private String filter; + + /** + * Creates an instance of KnowledgeAgentSearchActivityRecordQuery class. + */ + public KnowledgeAgentSearchActivityRecordQuery() { + } + + /** + * Get the search property: The search string. + * + * @return the search value. + */ + public String getSearch() { + return this.search; + } + + /** + * Set the search property: The search string. + * + * @param search the search value to set. + * @return the KnowledgeAgentSearchActivityRecordQuery object itself. + */ + public KnowledgeAgentSearchActivityRecordQuery setSearch(String search) { + this.search = search; + return this; + } + + /** + * Get the filter property: The filter string. + * + * @return the filter value. + */ + public String getFilter() { + return this.filter; + } + + /** + * Set the filter property: The filter string. + * + * @param filter the filter value to set. + * @return the KnowledgeAgentSearchActivityRecordQuery object itself. + */ + public KnowledgeAgentSearchActivityRecordQuery setFilter(String filter) { + this.filter = filter; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("search", this.search); + jsonWriter.writeStringField("filter", this.filter); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentSearchActivityRecordQuery from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentSearchActivityRecordQuery 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 KnowledgeAgentSearchActivityRecordQuery. + */ + public static KnowledgeAgentSearchActivityRecordQuery fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + KnowledgeAgentSearchActivityRecordQuery deserializedKnowledgeAgentSearchActivityRecordQuery + = new KnowledgeAgentSearchActivityRecordQuery(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("search".equals(fieldName)) { + deserializedKnowledgeAgentSearchActivityRecordQuery.search = reader.getString(); + } else if ("filter".equals(fieldName)) { + deserializedKnowledgeAgentSearchActivityRecordQuery.filter = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return deserializedKnowledgeAgentSearchActivityRecordQuery; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentSemanticRankerActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentSemanticRankerActivityRecord.java new file mode 100644 index 000000000000..531ce889f7f2 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/KnowledgeAgentSemanticRankerActivityRecord.java @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.agents.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Represents a semantic ranker activity record. + */ +@Fluent +public final class KnowledgeAgentSemanticRankerActivityRecord extends KnowledgeAgentActivityRecord { + /* + * The type of the activity record. + */ + private String type = "AzureSearchSemanticRanker"; + + /* + * The number of input tokens for the semantic ranker activity. + */ + private Integer inputTokens; + + /* + * The elapsed time in milliseconds for the model activity. + */ + private Integer elapsedMs; + + /** + * Creates an instance of KnowledgeAgentSemanticRankerActivityRecord class. + * + * @param id the id value to set. + */ + public KnowledgeAgentSemanticRankerActivityRecord(int id) { + super(id); + } + + /** + * Get the type property: The type of the activity record. + * + * @return the type value. + */ + @Override + public String getType() { + return this.type; + } + + /** + * Get the inputTokens property: The number of input tokens for the semantic ranker activity. + * + * @return the inputTokens value. + */ + public Integer getInputTokens() { + return this.inputTokens; + } + + /** + * Set the inputTokens property: The number of input tokens for the semantic ranker activity. + * + * @param inputTokens the inputTokens value to set. + * @return the KnowledgeAgentSemanticRankerActivityRecord object itself. + */ + public KnowledgeAgentSemanticRankerActivityRecord setInputTokens(Integer inputTokens) { + this.inputTokens = inputTokens; + return this; + } + + /** + * Get the elapsedMs property: The elapsed time in milliseconds for the model activity. + * + * @return the elapsedMs value. + */ + public Integer getElapsedMs() { + return this.elapsedMs; + } + + /** + * Set the elapsedMs property: The elapsed time in milliseconds for the model activity. + * + * @param elapsedMs the elapsedMs value to set. + * @return the KnowledgeAgentSemanticRankerActivityRecord object itself. + */ + public KnowledgeAgentSemanticRankerActivityRecord setElapsedMs(Integer elapsedMs) { + this.elapsedMs = elapsedMs; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("id", getId()); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeNumberField("inputTokens", this.inputTokens); + jsonWriter.writeNumberField("elapsedMs", this.elapsedMs); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentSemanticRankerActivityRecord from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentSemanticRankerActivityRecord 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 KnowledgeAgentSemanticRankerActivityRecord. + */ + public static KnowledgeAgentSemanticRankerActivityRecord fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean idFound = false; + int id = 0; + String type = "AzureSearchSemanticRanker"; + Integer inputTokens = null; + Integer elapsedMs = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getInt(); + idFound = true; + } else if ("type".equals(fieldName)) { + type = reader.getString(); + } else if ("inputTokens".equals(fieldName)) { + inputTokens = reader.getNullable(JsonReader::getInt); + } else if ("elapsedMs".equals(fieldName)) { + elapsedMs = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + if (idFound) { + KnowledgeAgentSemanticRankerActivityRecord deserializedKnowledgeAgentSemanticRankerActivityRecord + = new KnowledgeAgentSemanticRankerActivityRecord(id); + deserializedKnowledgeAgentSemanticRankerActivityRecord.type = type; + deserializedKnowledgeAgentSemanticRankerActivityRecord.inputTokens = inputTokens; + deserializedKnowledgeAgentSemanticRankerActivityRecord.elapsedMs = elapsedMs; + + return deserializedKnowledgeAgentSemanticRankerActivityRecord; + } + throw new IllegalStateException("Missing required property: id"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/package-info.java new file mode 100644 index 000000000000..075504dfacf0 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/models/package-info.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +/** + * Package containing the data models for KnowledgeAgentRetrievalClient. + * Client that can be used to query an agent. + */ +package com.azure.search.documents.agents.models; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/package-info.java new file mode 100644 index 000000000000..7caee133cffb --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/agents/package-info.java @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the clients and builders for Azure AI Search Knowledge Agents. + *

+ * This package provides the main entry points for interacting with Azure AI Search Knowledge Agents, including both synchronous and asynchronous clients, as well as fluent builders for client configuration. The clients enable advanced knowledge retrieval and aggregation scenarios across multiple data sources configured in your Azure AI Search instance. + *

+ *

+ * For more information about Azure AI Search Knowledge Agents, supported features, and usage guidelines, see the Azure documentation and the Azure SDK for Java guidelines. + *

+ */ +package com.azure.search.documents.agents; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DocumentsImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DocumentsImpl.java index e0fdfc6cf631..6fdde8e32c7c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DocumentsImpl.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DocumentsImpl.java @@ -88,20 +88,24 @@ Response countSync(@HostParam("endpoint") String endpoint, @HostParam("ind @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); @Post("/docs/search.post.search") - @ExpectedResponses({ 200 }) + @ExpectedResponses({ 200, 206 }) @UnexpectedResponseExceptionType(ErrorResponseException.class) Mono> searchPost(@HostParam("endpoint") String endpoint, @HostParam("indexName") String indexName, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchRequest searchRequest, Context context); + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @HeaderParam("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, + @HeaderParam("Accept") String accept, @BodyParam("application/json") SearchRequest searchRequest, + Context context); @Post("/docs/search.post.search") - @ExpectedResponses({ 200 }) + @ExpectedResponses({ 200, 206 }) @UnexpectedResponseExceptionType(ErrorResponseException.class) Response searchPostSync(@HostParam("endpoint") String endpoint, @HostParam("indexName") String indexName, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - @BodyParam("application/json") SearchRequest searchRequest, Context context); + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @HeaderParam("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, + @HeaderParam("Accept") String accept, @BodyParam("application/json") SearchRequest searchRequest, + Context context); @Get("/docs('{key}')") @ExpectedResponses({ 200 }) @@ -109,8 +113,9 @@ Response searchPostSync(@HostParam("endpoint") String end Mono>> get(@HostParam("endpoint") String endpoint, @HostParam("indexName") String indexName, @PathParam("key") String key, @QueryParam("$select") String selectedFields, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - Context context); + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @HeaderParam("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, + @HeaderParam("Accept") String accept, Context context); @Get("/docs('{key}')") @ExpectedResponses({ 200 }) @@ -118,8 +123,9 @@ Mono>> get(@HostParam("endpoint") String endpoint, Response> getSync(@HostParam("endpoint") String endpoint, @HostParam("indexName") String indexName, @PathParam("key") String key, @QueryParam("$select") String selectedFields, @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("Accept") String accept, - Context context); + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @HeaderParam("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, + @HeaderParam("Accept") String accept, Context context); @Post("/docs/search.post.suggest") @ExpectedResponses({ 200 }) @@ -275,6 +281,8 @@ public long count(RequestOptions requestOptions) { * Searches for documents in the index. * * @param searchRequest The definition of the Search request. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. @@ -284,14 +292,17 @@ public long count(RequestOptions requestOptions) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> searchPostWithResponseAsync(SearchRequest searchRequest, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> searchPostWithResponseAsync(searchRequest, requestOptions, context)); + String xMsQuerySourceAuthorization, RequestOptions requestOptions) { + return FluxUtil.withContext(context -> searchPostWithResponseAsync(searchRequest, xMsQuerySourceAuthorization, + requestOptions, context)); } /** * Searches for documents in the index. * * @param searchRequest The definition of the Search request. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -302,7 +313,7 @@ public Mono> searchPostWithResponseAsync(SearchR */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> searchPostWithResponseAsync(SearchRequest searchRequest, - RequestOptions requestOptions, Context context) { + String xMsQuerySourceAuthorization, RequestOptions requestOptions, Context context) { final String accept = "application/json; odata.metadata=none"; UUID xMsClientRequestIdInternal = null; if (requestOptions != null) { @@ -310,13 +321,15 @@ public Mono> searchPostWithResponseAsync(SearchR } UUID xMsClientRequestId = xMsClientRequestIdInternal; return service.searchPost(this.client.getEndpoint(), this.client.getIndexName(), this.client.getApiVersion(), - xMsClientRequestId, accept, searchRequest, context); + xMsClientRequestId, xMsQuerySourceAuthorization, accept, searchRequest, context); } /** * Searches for documents in the index. * * @param searchRequest The definition of the Search request. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. @@ -324,8 +337,9 @@ public Mono> searchPostWithResponseAsync(SearchR * @return response containing search results from an index on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono searchPostAsync(SearchRequest searchRequest, RequestOptions requestOptions) { - return searchPostWithResponseAsync(searchRequest, requestOptions) + public Mono searchPostAsync(SearchRequest searchRequest, String xMsQuerySourceAuthorization, + RequestOptions requestOptions) { + return searchPostWithResponseAsync(searchRequest, xMsQuerySourceAuthorization, requestOptions) .flatMap(res -> Mono.justOrEmpty(res.getValue())); } @@ -333,6 +347,8 @@ public Mono searchPostAsync(SearchRequest searchRequest, * Searches for documents in the index. * * @param searchRequest The definition of the Search request. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -341,9 +357,9 @@ public Mono searchPostAsync(SearchRequest searchRequest, * @return response containing search results from an index on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono searchPostAsync(SearchRequest searchRequest, RequestOptions requestOptions, - Context context) { - return searchPostWithResponseAsync(searchRequest, requestOptions, context) + public Mono searchPostAsync(SearchRequest searchRequest, String xMsQuerySourceAuthorization, + RequestOptions requestOptions, Context context) { + return searchPostWithResponseAsync(searchRequest, xMsQuerySourceAuthorization, requestOptions, context) .flatMap(res -> Mono.justOrEmpty(res.getValue())); } @@ -351,6 +367,8 @@ public Mono searchPostAsync(SearchRequest searchRequest, * Searches for documents in the index. * * @param searchRequest The definition of the Search request. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -360,7 +378,7 @@ public Mono searchPostAsync(SearchRequest searchRequest, */ @ServiceMethod(returns = ReturnType.SINGLE) public Response searchPostWithResponse(SearchRequest searchRequest, - RequestOptions requestOptions, Context context) { + String xMsQuerySourceAuthorization, RequestOptions requestOptions, Context context) { final String accept = "application/json; odata.metadata=none"; UUID xMsClientRequestIdInternal = null; if (requestOptions != null) { @@ -368,13 +386,16 @@ public Response searchPostWithResponse(SearchRequest sear } UUID xMsClientRequestId = xMsClientRequestIdInternal; return service.searchPostSync(this.client.getEndpoint(), this.client.getIndexName(), - this.client.getApiVersion(), xMsClientRequestId, accept, searchRequest, context); + this.client.getApiVersion(), xMsClientRequestId, xMsQuerySourceAuthorization, accept, searchRequest, + context); } /** * Searches for documents in the index. * * @param searchRequest The definition of the Search request. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. @@ -382,8 +403,10 @@ public Response searchPostWithResponse(SearchRequest sear * @return response containing search results from an index. */ @ServiceMethod(returns = ReturnType.SINGLE) - public SearchDocumentsResult searchPost(SearchRequest searchRequest, RequestOptions requestOptions) { - return searchPostWithResponse(searchRequest, requestOptions, Context.NONE).getValue(); + public SearchDocumentsResult searchPost(SearchRequest searchRequest, String xMsQuerySourceAuthorization, + RequestOptions requestOptions) { + return searchPostWithResponse(searchRequest, xMsQuerySourceAuthorization, requestOptions, Context.NONE) + .getValue(); } /** @@ -392,6 +415,8 @@ public SearchDocumentsResult searchPost(SearchRequest searchRequest, RequestOpti * @param key The key of the document to retrieve. * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing * from the returned document. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. @@ -401,8 +426,9 @@ public SearchDocumentsResult searchPost(SearchRequest searchRequest, RequestOpti */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono>> getWithResponseAsync(String key, List selectedFields, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(key, selectedFields, requestOptions, context)); + String xMsQuerySourceAuthorization, RequestOptions requestOptions) { + return FluxUtil.withContext( + context -> getWithResponseAsync(key, selectedFields, xMsQuerySourceAuthorization, requestOptions, context)); } /** @@ -411,6 +437,8 @@ public Mono>> getWithResponseAsync(String key, List * @param key The key of the document to retrieve. * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing * from the returned document. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -421,7 +449,7 @@ public Mono>> getWithResponseAsync(String key, List */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono>> getWithResponseAsync(String key, List selectedFields, - RequestOptions requestOptions, Context context) { + String xMsQuerySourceAuthorization, RequestOptions requestOptions, Context context) { final String accept = "application/json; odata.metadata=none"; UUID xMsClientRequestIdInternal = null; if (requestOptions != null) { @@ -434,7 +462,7 @@ public Mono>> getWithResponseAsync(String key, List .map(paramItemValue -> Objects.toString(paramItemValue, "")) .collect(Collectors.joining(",")); return service.get(this.client.getEndpoint(), this.client.getIndexName(), key, selectedFieldsConverted, - this.client.getApiVersion(), xMsClientRequestId, accept, context); + this.client.getApiVersion(), xMsClientRequestId, xMsQuerySourceAuthorization, accept, context); } /** @@ -443,6 +471,8 @@ public Mono>> getWithResponseAsync(String key, List * @param key The key of the document to retrieve. * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing * from the returned document. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. @@ -450,8 +480,9 @@ public Mono>> getWithResponseAsync(String key, List * @return a document retrieved via a document lookup operation on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getAsync(String key, List selectedFields, RequestOptions requestOptions) { - return getWithResponseAsync(key, selectedFields, requestOptions) + public Mono> getAsync(String key, List selectedFields, + String xMsQuerySourceAuthorization, RequestOptions requestOptions) { + return getWithResponseAsync(key, selectedFields, xMsQuerySourceAuthorization, requestOptions) .flatMap(res -> Mono.justOrEmpty(res.getValue())); } @@ -461,6 +492,8 @@ public Mono> getAsync(String key, List selectedField * @param key The key of the document to retrieve. * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing * from the returned document. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -469,9 +502,9 @@ public Mono> getAsync(String key, List selectedField * @return a document retrieved via a document lookup operation on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getAsync(String key, List selectedFields, RequestOptions requestOptions, - Context context) { - return getWithResponseAsync(key, selectedFields, requestOptions, context) + public Mono> getAsync(String key, List selectedFields, + String xMsQuerySourceAuthorization, RequestOptions requestOptions, Context context) { + return getWithResponseAsync(key, selectedFields, xMsQuerySourceAuthorization, requestOptions, context) .flatMap(res -> Mono.justOrEmpty(res.getValue())); } @@ -481,6 +514,8 @@ public Mono> getAsync(String key, List selectedField * @param key The key of the document to retrieve. * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing * from the returned document. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. @@ -490,7 +525,7 @@ public Mono> getAsync(String key, List selectedField */ @ServiceMethod(returns = ReturnType.SINGLE) public Response> getWithResponse(String key, List selectedFields, - RequestOptions requestOptions, Context context) { + String xMsQuerySourceAuthorization, RequestOptions requestOptions, Context context) { final String accept = "application/json; odata.metadata=none"; UUID xMsClientRequestIdInternal = null; if (requestOptions != null) { @@ -503,7 +538,7 @@ public Response> getWithResponse(String key, List se .map(paramItemValue -> Objects.toString(paramItemValue, "")) .collect(Collectors.joining(",")); return service.getSync(this.client.getEndpoint(), this.client.getIndexName(), key, selectedFieldsConverted, - this.client.getApiVersion(), xMsClientRequestId, accept, context); + this.client.getApiVersion(), xMsClientRequestId, xMsQuerySourceAuthorization, accept, context); } /** @@ -512,6 +547,8 @@ public Response> getWithResponse(String key, List se * @param key The key of the document to retrieve. * @param selectedFields List of field names to retrieve for the document; Any field not retrieved will be missing * from the returned document. + * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token + * is used to enforce security restrictions on documents. * @param requestOptions Parameter group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorResponseException thrown if the request is rejected by server. @@ -519,8 +556,10 @@ public Response> getWithResponse(String key, List se * @return a document retrieved via a document lookup operation. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Map get(String key, List selectedFields, RequestOptions requestOptions) { - return getWithResponse(key, selectedFields, requestOptions, Context.NONE).getValue(); + public Map get(String key, List selectedFields, String xMsQuerySourceAuthorization, + RequestOptions requestOptions) { + return getWithResponse(key, selectedFields, xMsQuerySourceAuthorization, requestOptions, Context.NONE) + .getValue(); } /** diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultConverter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultConverter.java index f5d5cc5fda84..9353873bb820 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultConverter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultConverter.java @@ -24,7 +24,8 @@ public static SearchResult map(com.azure.search.documents.implementation.models. SearchResult searchResult = new SearchResult(obj.getScore()); SearchResultHelper.setHighlights(searchResult, obj.getHighlights()); - SearchResultHelper.setSemanticSearchResults(searchResult, obj.getRerankerScore(), obj.getCaptions()); + SearchResultHelper.setSemanticSearchResults(searchResult, obj.getRerankerScore(), obj.getCaptions(), + obj.getRerankerBoostedScore()); SearchResultHelper.setDocumentDebugInfo(searchResult, obj.getDocumentDebugInfo()); SearchResultHelper.setAdditionalProperties(searchResult, new SearchDocument(obj.getAdditionalProperties())); SearchResultHelper.setJsonSerializer(searchResult, (JsonSerializer) serializer); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultHelper.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultHelper.java index 8388a0d2376e..2f168c8abe95 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultHelper.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultHelper.java @@ -32,7 +32,7 @@ public interface SearchResultAccessor { void setJsonSerializer(SearchResult searchResult, JsonSerializer jsonSerializer); void setSemanticSearchResults(SearchResult searchResult, Double rerankerScore, - List captions); + List captions, Double rerankerBoostedScore); void setDocumentDebugInfo(SearchResult searchResult, DocumentDebugInfo documentDebugInfo); } @@ -59,8 +59,8 @@ static void setJsonSerializer(SearchResult searchResult, JsonSerializer jsonSeri } static void setSemanticSearchResults(SearchResult searchResult, Double rerankerScore, - List captions) { - accessor.setSemanticSearchResults(searchResult, rerankerScore, captions); + List captions, Double rerankerBoostedScore) { + accessor.setSemanticSearchResults(searchResult, rerankerScore, captions, rerankerBoostedScore); } static void setDocumentDebugInfo(SearchResult searchResult, DocumentDebugInfo documentDebugInfo) { diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchResult.java index 8fc8485eedd9..36fe66fde0e9 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchResult.java @@ -34,6 +34,13 @@ public final class SearchResult implements JsonSerializable { */ private Double rerankerScore; + /* + * The relevance score computed by boosting the Reranker Score. Search results are sorted by the + * RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the Semantic Config. + * RerankerBoostedScore is only returned for queries of type 'semantic' + */ + private Double rerankerBoostedScore; + /* * Text fragments from the document that indicate the matching search terms, organized by each applicable field; * null if hit highlighting was not enabled for the query. @@ -85,6 +92,17 @@ public Double getRerankerScore() { return this.rerankerScore; } + /** + * Get the rerankerBoostedScore property: The relevance score computed by boosting the Reranker Score. Search + * results are sorted by the RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the + * Semantic Config. RerankerBoostedScore is only returned for queries of type 'semantic'. + * + * @return the rerankerBoostedScore value. + */ + public Double getRerankerBoostedScore() { + return this.rerankerBoostedScore; + } + /** * Get the highlights property: Text fragments from the document that indicate the matching search terms, organized * by each applicable field; null if hit highlighting was not enabled for the query. @@ -163,6 +181,7 @@ public static SearchResult fromJson(JsonReader jsonReader) throws IOException { boolean scoreFound = false; double score = 0.0; Double rerankerScore = null; + Double rerankerBoostedScore = null; Map> highlights = null; List captions = null; DocumentDebugInfo documentDebugInfo = null; @@ -176,6 +195,8 @@ public static SearchResult fromJson(JsonReader jsonReader) throws IOException { scoreFound = true; } else if ("@search.rerankerScore".equals(fieldName)) { rerankerScore = reader.getNullable(JsonReader::getDouble); + } else if ("@search.rerankerBoostedScore".equals(fieldName)) { + rerankerBoostedScore = reader.getNullable(JsonReader::getDouble); } else if ("@search.highlights".equals(fieldName)) { highlights = reader.readMap(reader1 -> reader1.readArray(reader2 -> reader2.getString())); } else if ("@search.captions".equals(fieldName)) { @@ -193,6 +214,7 @@ public static SearchResult fromJson(JsonReader jsonReader) throws IOException { if (scoreFound) { SearchResult deserializedSearchResult = new SearchResult(score); deserializedSearchResult.rerankerScore = rerankerScore; + deserializedSearchResult.rerankerBoostedScore = rerankerBoostedScore; deserializedSearchResult.highlights = highlights; deserializedSearchResult.captions = captions; deserializedSearchResult.documentDebugInfo = documentDebugInfo; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java index bad235ad4e31..6cfa70e36f8f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java @@ -15,6 +15,7 @@ import com.azure.search.documents.indexes.SimpleField; import com.azure.search.documents.indexes.models.FieldBuilderOptions; import com.azure.search.documents.indexes.models.LexicalAnalyzerName; +import com.azure.search.documents.indexes.models.PermissionFilter; import com.azure.search.documents.indexes.models.SearchField; import com.azure.search.documents.indexes.models.SearchFieldDataType; import com.azure.search.documents.indexes.models.VectorEncodingFormat; @@ -276,6 +277,7 @@ private static SearchField enrichWithAnnotation(SearchField searchField, Member boolean filterable; boolean sortable; boolean facetable; + String permissionFilter = null; boolean stored; boolean searchable = searchableField != null; String analyzerName = null; @@ -293,6 +295,7 @@ private static SearchField enrichWithAnnotation(SearchField searchField, Member filterable = simpleField.isFilterable(); sortable = simpleField.isSortable(); facetable = simpleField.isFacetable(); + permissionFilter = simpleField.permissionFilter(); } else { key = searchableField.isKey(); hidden = searchableField.isHidden(); @@ -300,6 +303,7 @@ private static SearchField enrichWithAnnotation(SearchField searchField, Member filterable = searchableField.isFilterable(); sortable = searchableField.isSortable(); facetable = searchableField.isFacetable(); + permissionFilter = searchableField.permissionFilter(); analyzerName = searchableField.analyzerName(); searchAnalyzerName = searchableField.searchAnalyzerName(); indexAnalyzerName = searchableField.indexAnalyzerName(); @@ -373,6 +377,10 @@ private static SearchField enrichWithAnnotation(SearchField searchField, Member searchField.setVectorEncodingFormat(VectorEncodingFormat.fromString(vectorEncodingFormat)); } + if (!CoreUtils.isNullOrEmpty(permissionFilter)) { + searchField.setPermissionFilter(PermissionFilter.fromString(permissionFilter)); + } + if (!CoreUtils.isNullOrEmpty(synonymMapNames)) { List synonymMaps = Arrays.stream(searchableField.synonymMapNames()) .filter(synonym -> !synonym.trim().isEmpty()) diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexAsyncClient.java index 0439674f51a8..c3f380552e4d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexAsyncClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexAsyncClient.java @@ -26,6 +26,7 @@ import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; import com.azure.search.documents.indexes.models.FieldBuilderOptions; import com.azure.search.documents.indexes.models.IndexStatisticsSummary; +import com.azure.search.documents.indexes.models.KnowledgeAgent; import com.azure.search.documents.indexes.models.SearchField; import com.azure.search.documents.indexes.models.SearchIndex; import com.azure.search.documents.indexes.models.SearchIndexStatistics; @@ -1266,4 +1267,201 @@ PagedFlux getIndexStatsSummary(Context context) { return pagedFluxError(LOGGER, mappedException); } } + + /** + * Creates a new agent. + * + * @param knowledgeAgent The definition of the agent to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createKnowledgeAgent(KnowledgeAgent knowledgeAgent) { + return createKnowledgeAgentWithResponse(knowledgeAgent, Context.NONE).map(Response::getValue); + } + + /** + * Creates a new agent. + * + * @param knowledgeAgent The definition of the agent to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createKnowledgeAgentWithResponse(KnowledgeAgent knowledgeAgent) { + return withContext(context -> createKnowledgeAgentWithResponse(knowledgeAgent, context)); + } + + Mono> createKnowledgeAgentWithResponse(KnowledgeAgent knowledgeAgent, Context context) { + try { + return restClient.getKnowledgeAgents() + .createWithResponseAsync(knowledgeAgent, null, context) + .onErrorMap(MappingUtils::exceptionMapper); + } catch (RuntimeException ex) { + return monoError(LOGGER, ex); + } + } + + /** + * Creates a new agent or updates an agent if it already exists. + * + * @param agentName The name of the agent to create or update. + * @param knowledgeAgent The definition of the agent to create or update. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdateKnowledgeAgent(String agentName, KnowledgeAgent knowledgeAgent, + String ifMatch, String ifNoneMatch) { + return createOrUpdateKnowledgeAgentWithResponse(agentName, knowledgeAgent, ifMatch, ifNoneMatch, Context.NONE) + .map(Response::getValue); + } + + /** + * Creates a new agent or updates an agent if it already exists. + * + * @param agentName The name of the agent to create or update. + * @param knowledgeAgent The definition of the agent to create or update. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateKnowledgeAgentWithResponse(String agentName, + KnowledgeAgent knowledgeAgent, String ifMatch, String ifNoneMatch) { + return withContext(context -> createOrUpdateKnowledgeAgentWithResponse(agentName, knowledgeAgent, ifMatch, + ifNoneMatch, context)); + } + + Mono> createOrUpdateKnowledgeAgentWithResponse(String agentName, + KnowledgeAgent knowledgeAgent, String ifMatch, String ifNoneMatch, Context context) { + try { + return restClient.getKnowledgeAgents() + .createOrUpdateWithResponseAsync(agentName, knowledgeAgent, ifMatch, null, null, context) + .onErrorMap(MappingUtils::exceptionMapper); + } catch (RuntimeException ex) { + return monoError(LOGGER, ex); + } + } + + /** + * Retrieves an agent definition. + * + * @param agentName The name of the agent to retrieve. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getKnowledgeAgent(String agentName) { + return getKnowledgeAgentWithResponse(agentName, Context.NONE).map(Response::getValue); + + } + + /** + * Retrieves an agent definition. + * + * @param agentName The name of the agent to retrieve. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getKnowledgeAgentWithResponse(String agentName) { + return withContext(context -> getKnowledgeAgentWithResponse(agentName, context)); + } + + Mono> getKnowledgeAgentWithResponse(String agentName, Context context) { + try { + return restClient.getKnowledgeAgents() + .getWithResponseAsync(agentName, null, context) + .onErrorMap(MappingUtils::exceptionMapper); + } catch (RuntimeException ex) { + return monoError(LOGGER, ex); + } + } + + /** + * Lists all agents available for a search service. + * + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listKnowledgeAgents() { + try { + return restClient.getKnowledgeAgents().listAsync(null, Context.NONE); + } catch (RuntimeException ex) { + RuntimeException mappedException = (RuntimeException) MappingUtils.exceptionMapper(ex); + return pagedFluxError(LOGGER, mappedException); + } + } + + /** + * Deletes an existing agent. + * + * @param agentName The name of the agent to delete. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @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. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono deleteKnowledgeAgent(String agentName, String ifMatch, String ifNoneMatch) { + return deleteKnowledgeAgentWithResponse(agentName, ifMatch, ifNoneMatch, Context.NONE) + .flatMap(FluxUtil::toMono); + } + + /** + * Deletes an existing agent. + * + * @param agentName The name of the agent to delete. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteKnowledgeAgentWithResponse(String agentName, String ifMatch, String ifNoneMatch) { + return withContext(context -> deleteKnowledgeAgentWithResponse(agentName, ifMatch, ifNoneMatch, context)); + } + + Mono> deleteKnowledgeAgentWithResponse(String agentName, String ifMatch, String ifNoneMatch, + Context context) { + try { + return restClient.getKnowledgeAgents() + .deleteWithResponseAsync(agentName, ifMatch, ifNoneMatch, null, context) + .onErrorMap(MappingUtils::exceptionMapper); + } catch (RuntimeException ex) { + return monoError(LOGGER, ex); + } + + } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java index 028a3b9c9b63..79ab904d9f58 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java @@ -24,6 +24,7 @@ import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; import com.azure.search.documents.indexes.models.FieldBuilderOptions; import com.azure.search.documents.indexes.models.IndexStatisticsSummary; +import com.azure.search.documents.indexes.models.KnowledgeAgent; import com.azure.search.documents.indexes.models.LexicalAnalyzerName; import com.azure.search.documents.indexes.models.LexicalTokenizerName; import com.azure.search.documents.indexes.models.SearchField; @@ -1308,4 +1309,181 @@ public PagedIterable getIndexStatsSummary(Context contex public static List buildSearchFields(Class model, FieldBuilderOptions options) { return SearchIndexAsyncClient.buildSearchFields(model, options); } + + /** + * Creates a new agent. + * + * @param knowledgeAgent The definition of the agent to create. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeAgent createKnowledgeAgent(KnowledgeAgent knowledgeAgent) { + return createKnowledgeAgentWithResponse(knowledgeAgent, Context.NONE).getValue(); + + } + + /** + * Creates a new agent. + * + * @param knowledgeAgent The definition of the agent to create. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createKnowledgeAgentWithResponse(KnowledgeAgent knowledgeAgent, Context context) { + return Utility.executeRestCallWithExceptionHandling( + () -> restClient.getKnowledgeAgents().createWithResponse(knowledgeAgent, null, context), LOGGER); + + } + + /** + * Creates a new agent or updates an agent if it already exists. + * + * @param agentName The name of the agent to create or update. + * @param knowledgeAgent The definition of the agent to create or update. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeAgent createOrUpdateKnowledgeAgent(String agentName, KnowledgeAgent knowledgeAgent, String ifMatch, + String ifNoneMatch) { + return createOrUpdateKnowledgeAgentWithResponse(agentName, knowledgeAgent, ifMatch, ifNoneMatch, Context.NONE) + .getValue(); + } + + /** + * Creates a new agent or updates an agent if it already exists. + * + * @param agentName The name of the agent to create or update. + * @param knowledgeAgent The definition of the agent to create or update. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateKnowledgeAgentWithResponse(String agentName, + KnowledgeAgent knowledgeAgent, String ifMatch, String ifNoneMatch, Context context) { + return Utility + .executeRestCallWithExceptionHandling( + () -> restClient.getKnowledgeAgents() + .createOrUpdateWithResponse(agentName, knowledgeAgent, ifMatch, ifNoneMatch, null, context), + LOGGER); + } + + /** + * Retrieves an agent definition. + * + * @param agentName The name of the agent to retrieve. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeAgent getKnowledgeAgent(String agentName) { + return getKnowledgeAgentWithResponse(agentName, Context.NONE).getValue(); + + } + + /** + * Retrieves an agent definition. + * + * @param agentName The name of the agent to retrieve. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getKnowledgeAgentWithResponse(String agentName, Context context) { + return Utility.executeRestCallWithExceptionHandling( + () -> restClient.getKnowledgeAgents().getWithResponse(agentName, null, context), LOGGER); + } + + /** + * Lists all agents available for a search service. + * + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listKnowledgeAgents() { + return listKnowledgeAgents(Context.NONE); + } + + /** + * Lists all agents available for a search service. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listKnowledgeAgents(Context context) { + return Utility.executeRestCallWithExceptionHandling(() -> restClient.getKnowledgeAgents().list(null, context), + LOGGER); + } + + /** + * Deletes an existing agent. + * + * @param agentName The name of the agent to delete. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void deleteKnowledgeAgent(String agentName, String ifMatch, String ifNoneMatch) { + deleteKnowledgeAgentWithResponse(agentName, ifMatch, ifNoneMatch, Context.NONE).getValue(); + } + + /** + * Deletes an existing agent. + * + * @param agentName The name of the agent to delete. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteKnowledgeAgentWithResponse(String agentName, String ifMatch, String ifNoneMatch, + Context context) { + return Utility.executeRestCallWithExceptionHandling( + () -> restClient.getKnowledgeAgents().deleteWithResponse(agentName, ifMatch, ifNoneMatch, null, context), + LOGGER); + + } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java index 20a9bf9d6e6d..bc220d94b90e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java @@ -15,9 +15,11 @@ import com.azure.search.documents.SearchServiceVersion; import com.azure.search.documents.implementation.util.MappingUtils; import com.azure.search.documents.indexes.implementation.SearchServiceClientImpl; +import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; import com.azure.search.documents.indexes.implementation.models.ListDataSourcesResult; import com.azure.search.documents.indexes.implementation.models.ListIndexersResult; import com.azure.search.documents.indexes.implementation.models.ListSkillsetsResult; +import com.azure.search.documents.indexes.models.IndexerResyncBody; import com.azure.search.documents.indexes.models.SearchIndexer; import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; import com.azure.search.documents.indexes.models.SearchIndexerSkillset; @@ -1668,4 +1670,45 @@ Mono> deleteSkillsetWithResponse(String skillsetName, String eTag return monoError(LOGGER, ex); } } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer. + * + * @param indexerName The name of the indexer to resync for. + * @param indexerResync The indexerResync parameter. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @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. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono resync(String indexerName, IndexerResyncBody indexerResync) { + return resyncWithResponse(indexerName, indexerResync).flatMap(FluxUtil::toMono); + } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer. + * + * @param indexerName The name of the indexer to resync for. + * @param indexerResync The indexerResync parameter. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> resyncWithResponse(String indexerName, IndexerResyncBody indexerResync) { + return withContext(context -> resyncWithResponseAsync(indexerName, indexerResync, context)); + } + + Mono> resyncWithResponseAsync(String indexerName, IndexerResyncBody indexerResync, Context context) { + try { + return restClient.getIndexers() + .resyncWithResponseAsync(indexerName, indexerResync, null, context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(Function.identity()); + } catch (RuntimeException ex) { + return monoError(LOGGER, ex); + } + } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java index abc4de3a661a..d09d25b3f7a2 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java @@ -15,9 +15,11 @@ import com.azure.search.documents.implementation.util.MappingUtils; import com.azure.search.documents.implementation.util.Utility; import com.azure.search.documents.indexes.implementation.SearchServiceClientImpl; +import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; import com.azure.search.documents.indexes.implementation.models.ListDataSourcesResult; import com.azure.search.documents.indexes.implementation.models.ListIndexersResult; import com.azure.search.documents.indexes.implementation.models.ListSkillsetsResult; +import com.azure.search.documents.indexes.models.IndexerResyncBody; import com.azure.search.documents.indexes.models.SearchIndexer; import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; import com.azure.search.documents.indexes.models.SearchIndexerSkillset; @@ -1613,4 +1615,36 @@ public Response deleteSkillsetWithResponse(SearchIndexerSkillset skillset, return Utility.executeRestCallWithExceptionHandling( () -> restClient.getSkillsets().deleteWithResponse(skillset.getName(), eTag, null, null, context), LOGGER); } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer. + * + * @param indexerName The name of the indexer to resync for. + * @param indexerResync The indexerResync parameter. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void resync(String indexerName, IndexerResyncBody indexerResync) { + resyncWithResponse(indexerName, indexerResync, Context.NONE).getValue(); + } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer. + * + * @param indexerName The name of the indexer to resync for. + * @param indexerResync The indexerResync parameter. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response resyncWithResponse(String indexerName, IndexerResyncBody indexerResync, Context context) { + return Utility.executeRestCallWithExceptionHandling( + () -> restClient.getIndexers().resyncWithResponse(indexerName, indexerResync, null, context), LOGGER); + } + } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java index 6579d4de3e24..e7ed82927c88 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java @@ -42,6 +42,13 @@ */ boolean isFacetable() default false; + /** + * Indicates if the field or method should be used as a permission filter {@link SearchField field}. + * + * @return A flag indicating if the field or method should generate as a filterable {@link SearchField field}. + */ + String permissionFilter() default ""; + /** * Indicates if the field or method should generate as a sortable {@link SearchField field}. * diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SimpleField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SimpleField.java index a0d651d9888d..25779193e291 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SimpleField.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SimpleField.java @@ -52,4 +52,11 @@ * @return A flag indicating if the field or method should generate as a filterable {@link SearchField field}. */ boolean isFilterable() default false; + + /** + * A value indicating whether the field should be used as a permission filter. + * + * @return A flag indicating if the field or method should generate as a permission filter {@link SearchField field}. + */ + String permissionFilter() default ""; } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexersImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexersImpl.java index 966d17df801d..369de3af1a94 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexersImpl.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexersImpl.java @@ -29,6 +29,7 @@ import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; import com.azure.search.documents.indexes.implementation.models.ListIndexersResult; import com.azure.search.documents.indexes.implementation.models.RequestOptions; +import com.azure.search.documents.indexes.models.IndexerResyncBody; import com.azure.search.documents.indexes.models.SearchIndexer; import com.azure.search.documents.indexes.models.SearchIndexerStatus; import java.util.UUID; @@ -97,6 +98,23 @@ Response resetDocsSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, @BodyParam("application/json") DocumentKeysOrIds keysOrIds, Context context); + @Post("/indexers('{indexerName}')/search.resync") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Mono> resync(@HostParam("endpoint") String endpoint, + @PathParam("indexerName") String indexerName, + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @BodyParam("application/json") IndexerResyncBody indexerResync, Context context); + + @Post("/indexers('{indexerName}')/search.resync") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Response resyncSync(@HostParam("endpoint") String endpoint, @PathParam("indexerName") String indexerName, + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @BodyParam("application/json") IndexerResyncBody indexerResync, Context context); + @Post("/indexers('{indexerName}')/search.run") @ExpectedResponses({ 202 }) @UnexpectedResponseExceptionType(ErrorResponseException.class) @@ -457,6 +475,124 @@ public void resetDocs(String indexerName, Boolean overwrite, DocumentKeysOrIds k resetDocsWithResponse(indexerName, overwrite, keysOrIds, requestOptions, Context.NONE); } + /** + * Resync selective options from the datasource to be re-ingested by the indexer. + * + * @param indexerName The name of the indexer to resync for. + * @param indexerResync The indexerResync parameter. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> resyncWithResponseAsync(String indexerName, IndexerResyncBody indexerResync, + RequestOptions requestOptions) { + return FluxUtil + .withContext(context -> resyncWithResponseAsync(indexerName, indexerResync, requestOptions, context)); + } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer. + * + * @param indexerName The name of the indexer to resync for. + * @param indexerResync The indexerResync parameter. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> resyncWithResponseAsync(String indexerName, IndexerResyncBody indexerResync, + RequestOptions requestOptions, Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.resync(this.client.getEndpoint(), indexerName, xMsClientRequestId, this.client.getApiVersion(), + accept, indexerResync, context); + } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer. + * + * @param indexerName The name of the indexer to resync for. + * @param indexerResync The indexerResync parameter. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @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. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono resyncAsync(String indexerName, IndexerResyncBody indexerResync, RequestOptions requestOptions) { + return resyncWithResponseAsync(indexerName, indexerResync, requestOptions).flatMap(ignored -> Mono.empty()); + } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer. + * + * @param indexerName The name of the indexer to resync for. + * @param indexerResync The indexerResync parameter. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @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. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono resyncAsync(String indexerName, IndexerResyncBody indexerResync, RequestOptions requestOptions, + Context context) { + return resyncWithResponseAsync(indexerName, indexerResync, requestOptions, context) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer. + * + * @param indexerName The name of the indexer to resync for. + * @param indexerResync The indexerResync parameter. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response resyncWithResponse(String indexerName, IndexerResyncBody indexerResync, + RequestOptions requestOptions, Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.resyncSync(this.client.getEndpoint(), indexerName, xMsClientRequestId, + this.client.getApiVersion(), accept, indexerResync, context); + } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer. + * + * @param indexerName The name of the indexer to resync for. + * @param indexerResync The indexerResync parameter. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void resync(String indexerName, IndexerResyncBody indexerResync, RequestOptions requestOptions) { + resyncWithResponse(indexerName, indexerResync, requestOptions, Context.NONE); + } + /** * Runs an indexer on-demand. * diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/KnowledgeAgentsImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/KnowledgeAgentsImpl.java new file mode 100644 index 000000000000..c90672301675 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/KnowledgeAgentsImpl.java @@ -0,0 +1,811 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.implementation; + +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.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +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.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.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.search.documents.indexes.implementation.models.ErrorResponseException; +import com.azure.search.documents.indexes.implementation.models.RequestOptions; +import com.azure.search.documents.indexes.models.KnowledgeAgent; +import com.azure.search.documents.indexes.models.ListKnowledgeAgentsResult; +import java.util.UUID; +import reactor.core.publisher.Mono; + +/** + * An instance of this class provides access to all the operations defined in KnowledgeAgents. + */ +public final class KnowledgeAgentsImpl { + /** + * The proxy service used to perform REST calls. + */ + private final KnowledgeAgentsService service; + + /** + * The service client containing this operation class. + */ + private final SearchServiceClientImpl client; + + /** + * Initializes an instance of KnowledgeAgentsImpl. + * + * @param client the instance of the service client containing this operation class. + */ + KnowledgeAgentsImpl(SearchServiceClientImpl client) { + this.service + = RestProxy.create(KnowledgeAgentsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for SearchServiceClientKnowledgeAgents to be used by the proxy service to + * perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "SearchServiceClientK") + public interface KnowledgeAgentsService { + @Put("/agents('{agentName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Mono> createOrUpdate(@HostParam("endpoint") String endpoint, + @PathParam("agentName") String agentName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @HeaderParam("If-Match") String ifMatch, @HeaderParam("If-None-Match") String ifNoneMatch, + @HeaderParam("Prefer") String prefer, @QueryParam("api-version") String apiVersion, + @HeaderParam("Accept") String accept, @BodyParam("application/json") KnowledgeAgent knowledgeAgent, + Context context); + + @Put("/agents('{agentName}')") + @ExpectedResponses({ 200, 201 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Response createOrUpdateSync(@HostParam("endpoint") String endpoint, + @PathParam("agentName") String agentName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @HeaderParam("If-Match") String ifMatch, @HeaderParam("If-None-Match") String ifNoneMatch, + @HeaderParam("Prefer") String prefer, @QueryParam("api-version") String apiVersion, + @HeaderParam("Accept") String accept, @BodyParam("application/json") KnowledgeAgent knowledgeAgent, + Context context); + + @Delete("/agents('{agentName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Mono> delete(@HostParam("endpoint") String endpoint, @PathParam("agentName") String agentName, + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, + @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, + @HeaderParam("Accept") String accept, Context context); + + @Delete("/agents('{agentName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Response deleteSync(@HostParam("endpoint") String endpoint, @PathParam("agentName") String agentName, + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, @HeaderParam("If-Match") String ifMatch, + @HeaderParam("If-None-Match") String ifNoneMatch, @QueryParam("api-version") String apiVersion, + @HeaderParam("Accept") String accept, Context context); + + @Get("/agents('{agentName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Mono> get(@HostParam("endpoint") String endpoint, + @PathParam("agentName") String agentName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Get("/agents('{agentName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Response getSync(@HostParam("endpoint") String endpoint, + @PathParam("agentName") String agentName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Get("/agents") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Mono> list(@HostParam("endpoint") String endpoint, + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Get("/agents") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Response listSync(@HostParam("endpoint") String endpoint, + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); + + @Post("/agents") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Mono> create(@HostParam("endpoint") String endpoint, + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @BodyParam("application/json") KnowledgeAgent knowledgeAgent, Context context); + + @Post("/agents") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(ErrorResponseException.class) + Response createSync(@HostParam("endpoint") String endpoint, + @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @BodyParam("application/json") KnowledgeAgent knowledgeAgent, Context context); + } + + /** + * Creates a new agent or updates an agent if it already exists. + * + * @param agentName The name of the agent to create or update. + * @param knowledgeAgent The definition of the agent to create or update. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponseAsync(String agentName, + KnowledgeAgent knowledgeAgent, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { + return FluxUtil.withContext(context -> createOrUpdateWithResponseAsync(agentName, knowledgeAgent, ifMatch, + ifNoneMatch, requestOptions, context)); + } + + /** + * Creates a new agent or updates an agent if it already exists. + * + * @param agentName The name of the agent to create or update. + * @param knowledgeAgent The definition of the agent to create or update. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateWithResponseAsync(String agentName, + KnowledgeAgent knowledgeAgent, String ifMatch, String ifNoneMatch, RequestOptions requestOptions, + Context context) { + final String prefer = "return=representation"; + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.createOrUpdate(this.client.getEndpoint(), agentName, xMsClientRequestId, ifMatch, ifNoneMatch, + prefer, this.client.getApiVersion(), accept, knowledgeAgent, context); + } + + /** + * Creates a new agent or updates an agent if it already exists. + * + * @param agentName The name of the agent to create or update. + * @param knowledgeAgent The definition of the agent to create or update. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdateAsync(String agentName, KnowledgeAgent knowledgeAgent, String ifMatch, + String ifNoneMatch, RequestOptions requestOptions) { + return createOrUpdateWithResponseAsync(agentName, knowledgeAgent, ifMatch, ifNoneMatch, requestOptions) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Creates a new agent or updates an agent if it already exists. + * + * @param agentName The name of the agent to create or update. + * @param knowledgeAgent The definition of the agent to create or update. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdateAsync(String agentName, KnowledgeAgent knowledgeAgent, String ifMatch, + String ifNoneMatch, RequestOptions requestOptions, Context context) { + return createOrUpdateWithResponseAsync(agentName, knowledgeAgent, ifMatch, ifNoneMatch, requestOptions, context) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Creates a new agent or updates an agent if it already exists. + * + * @param agentName The name of the agent to create or update. + * @param knowledgeAgent The definition of the agent to create or update. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateWithResponse(String agentName, KnowledgeAgent knowledgeAgent, + String ifMatch, String ifNoneMatch, RequestOptions requestOptions, Context context) { + final String prefer = "return=representation"; + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.createOrUpdateSync(this.client.getEndpoint(), agentName, xMsClientRequestId, ifMatch, + ifNoneMatch, prefer, this.client.getApiVersion(), accept, knowledgeAgent, context); + } + + /** + * Creates a new agent or updates an agent if it already exists. + * + * @param agentName The name of the agent to create or update. + * @param knowledgeAgent The definition of the agent to create or update. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeAgent createOrUpdate(String agentName, KnowledgeAgent knowledgeAgent, String ifMatch, + String ifNoneMatch, RequestOptions requestOptions) { + return createOrUpdateWithResponse(agentName, knowledgeAgent, ifMatch, ifNoneMatch, requestOptions, Context.NONE) + .getValue(); + } + + /** + * Deletes an existing agent. + * + * @param agentName The name of the agent to delete. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponseAsync(String agentName, String ifMatch, String ifNoneMatch, + RequestOptions requestOptions) { + return FluxUtil + .withContext(context -> deleteWithResponseAsync(agentName, ifMatch, ifNoneMatch, requestOptions, context)); + } + + /** + * Deletes an existing agent. + * + * @param agentName The name of the agent to delete. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> deleteWithResponseAsync(String agentName, String ifMatch, String ifNoneMatch, + RequestOptions requestOptions, Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.delete(this.client.getEndpoint(), agentName, xMsClientRequestId, ifMatch, ifNoneMatch, + this.client.getApiVersion(), accept, context); + } + + /** + * Deletes an existing agent. + * + * @param agentName The name of the agent to delete. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @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. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono deleteAsync(String agentName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { + return deleteWithResponseAsync(agentName, ifMatch, ifNoneMatch, requestOptions) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Deletes an existing agent. + * + * @param agentName The name of the agent to delete. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @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. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono deleteAsync(String agentName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions, + Context context) { + return deleteWithResponseAsync(agentName, ifMatch, ifNoneMatch, requestOptions, context) + .flatMap(ignored -> Mono.empty()); + } + + /** + * Deletes an existing agent. + * + * @param agentName The name of the agent to delete. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response deleteWithResponse(String agentName, String ifMatch, String ifNoneMatch, + RequestOptions requestOptions, Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.deleteSync(this.client.getEndpoint(), agentName, xMsClientRequestId, ifMatch, ifNoneMatch, + this.client.getApiVersion(), accept, context); + } + + /** + * Deletes an existing agent. + * + * @param agentName The name of the agent to delete. + * @param ifMatch Defines the If-Match condition. The operation will be performed only if the ETag on the server + * matches this value. + * @param ifNoneMatch Defines the If-None-Match condition. The operation will be performed only if the ETag on the + * server does not match this value. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public void delete(String agentName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { + deleteWithResponse(agentName, ifMatch, ifNoneMatch, requestOptions, Context.NONE); + } + + /** + * Retrieves an agent definition. + * + * @param agentName The name of the agent to retrieve. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponseAsync(String agentName, RequestOptions requestOptions) { + return FluxUtil.withContext(context -> getWithResponseAsync(agentName, requestOptions, context)); + } + + /** + * Retrieves an agent definition. + * + * @param agentName The name of the agent to retrieve. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getWithResponseAsync(String agentName, RequestOptions requestOptions, + Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.get(this.client.getEndpoint(), agentName, xMsClientRequestId, this.client.getApiVersion(), + accept, context); + } + + /** + * Retrieves an agent definition. + * + * @param agentName The name of the agent to retrieve. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getAsync(String agentName, RequestOptions requestOptions) { + return getWithResponseAsync(agentName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Retrieves an agent definition. + * + * @param agentName The name of the agent to retrieve. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getAsync(String agentName, RequestOptions requestOptions, Context context) { + return getWithResponseAsync(agentName, requestOptions, context) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Retrieves an agent definition. + * + * @param agentName The name of the agent to retrieve. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getWithResponse(String agentName, RequestOptions requestOptions, Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.getSync(this.client.getEndpoint(), agentName, xMsClientRequestId, this.client.getApiVersion(), + accept, context); + } + + /** + * Retrieves an agent definition. + * + * @param agentName The name of the agent to retrieve. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeAgent get(String agentName, RequestOptions requestOptions) { + return getWithResponse(agentName, requestOptions, Context.NONE).getValue(); + } + + /** + * Lists all agents available for a search service. + * + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link PagedResponse} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return FluxUtil + .withContext(context -> service.list(this.client.getEndpoint(), xMsClientRequestId, + this.client.getApiVersion(), accept, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().getKnowledgeAgents(), null, null)); + } + + /** + * Lists all agents available for a search service. + * + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link PagedResponse} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listSinglePageAsync(RequestOptions requestOptions, Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.list(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, context) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().getKnowledgeAgents(), null, null)); + } + + /** + * Lists all agents available for a search service. + * + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listAsync(RequestOptions requestOptions) { + return new PagedFlux<>(() -> listSinglePageAsync(requestOptions)); + } + + /** + * Lists all agents available for a search service. + * + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listAsync(RequestOptions requestOptions, Context context) { + return new PagedFlux<>(() -> listSinglePageAsync(requestOptions, context)); + } + + /** + * Lists all agents available for a search service. + * + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PagedResponse listSinglePage(RequestOptions requestOptions) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + Response res = service.listSync(this.client.getEndpoint(), xMsClientRequestId, + this.client.getApiVersion(), accept, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().getKnowledgeAgents(), null, null); + } + + /** + * Lists all agents available for a search service. + * + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public PagedResponse listSinglePage(RequestOptions requestOptions, Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + Response res = service.listSync(this.client.getEndpoint(), xMsClientRequestId, + this.client.getApiVersion(), accept, context); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + res.getValue().getKnowledgeAgents(), null, null); + } + + /** + * Lists all agents available for a search service. + * + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(RequestOptions requestOptions) { + return new PagedIterable<>(() -> listSinglePage(requestOptions, Context.NONE)); + } + + /** + * Lists all agents available for a search service. + * + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable list(RequestOptions requestOptions, Context context) { + return new PagedIterable<>(() -> listSinglePage(requestOptions, context)); + } + + /** + * Creates a new agent. + * + * @param knowledgeAgent The definition of the agent to create. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponseAsync(KnowledgeAgent knowledgeAgent, + RequestOptions requestOptions) { + return FluxUtil.withContext(context -> createWithResponseAsync(knowledgeAgent, requestOptions, context)); + } + + /** + * Creates a new agent. + * + * @param knowledgeAgent The definition of the agent to create. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createWithResponseAsync(KnowledgeAgent knowledgeAgent, + RequestOptions requestOptions, Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.create(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, + knowledgeAgent, context); + } + + /** + * Creates a new agent. + * + * @param knowledgeAgent The definition of the agent to create. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createAsync(KnowledgeAgent knowledgeAgent, RequestOptions requestOptions) { + return createWithResponseAsync(knowledgeAgent, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Creates a new agent. + * + * @param knowledgeAgent The definition of the agent to create. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createAsync(KnowledgeAgent knowledgeAgent, RequestOptions requestOptions, + Context context) { + return createWithResponseAsync(knowledgeAgent, requestOptions, context) + .flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * Creates a new agent. + * + * @param knowledgeAgent The definition of the agent to create. + * @param requestOptions Parameter group. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response body along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createWithResponse(KnowledgeAgent knowledgeAgent, RequestOptions requestOptions, + Context context) { + final String accept = "application/json; odata.metadata=minimal"; + UUID xMsClientRequestIdInternal = null; + if (requestOptions != null) { + xMsClientRequestIdInternal = requestOptions.getXMsClientRequestId(); + } + UUID xMsClientRequestId = xMsClientRequestIdInternal; + return service.createSync(this.client.getEndpoint(), xMsClientRequestId, this.client.getApiVersion(), accept, + knowledgeAgent, context); + } + + /** + * Creates a new agent. + * + * @param knowledgeAgent The definition of the agent to create. + * @param requestOptions Parameter group. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeAgent create(KnowledgeAgent knowledgeAgent, RequestOptions requestOptions) { + return createWithResponse(knowledgeAgent, requestOptions, Context.NONE).getValue(); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SearchServiceClientImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SearchServiceClientImpl.java index af4a52d300f6..412439914de8 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SearchServiceClientImpl.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SearchServiceClientImpl.java @@ -103,6 +103,20 @@ public SerializerAdapter getSerializerAdapter() { return this.serializerAdapter; } + /** + * The KnowledgeAgentsImpl object to access its operations. + */ + private final KnowledgeAgentsImpl knowledgeAgents; + + /** + * Gets the KnowledgeAgentsImpl object to access its operations. + * + * @return the KnowledgeAgentsImpl object. + */ + public KnowledgeAgentsImpl getKnowledgeAgents() { + return this.knowledgeAgents; + } + /** * The DataSourcesImpl object to access its operations. */ @@ -223,6 +237,7 @@ public SearchServiceClientImpl(HttpPipeline httpPipeline, SerializerAdapter seri this.serializerAdapter = serializerAdapter; this.endpoint = endpoint; this.apiVersion = apiVersion; + this.knowledgeAgents = new KnowledgeAgentsImpl(this); this.dataSources = new DataSourcesImpl(this); this.indexers = new IndexersImpl(this); this.skillsets = new SkillsetsImpl(this); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIFoundryModelCatalogName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIFoundryModelCatalogName.java index 9ad3cc9008ef..178e5bf23122 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIFoundryModelCatalogName.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIFoundryModelCatalogName.java @@ -48,6 +48,11 @@ public final class AIFoundryModelCatalogName extends ExpandableStringEnum { + /** + * Passes any extra parameters directly to the model. + */ + public static final ChatCompletionExtraParametersBehavior PASS_THROUGH = fromString("passThrough"); + + /** + * Drops all extra parameters. + */ + public static final ChatCompletionExtraParametersBehavior DROP = fromString("drop"); + + /** + * Raises an error if any extra parameter is present. + */ + public static final ChatCompletionExtraParametersBehavior ERROR = fromString("error"); + + /** + * Creates a new instance of ChatCompletionExtraParametersBehavior value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ChatCompletionExtraParametersBehavior() { + } + + /** + * Creates or finds a ChatCompletionExtraParametersBehavior from its string representation. + * + * @param name a name to look for. + * @return the corresponding ChatCompletionExtraParametersBehavior. + */ + public static ChatCompletionExtraParametersBehavior fromString(String name) { + return fromString(name, ChatCompletionExtraParametersBehavior.class); + } + + /** + * Gets known ChatCompletionExtraParametersBehavior values. + * + * @return known ChatCompletionExtraParametersBehavior values. + */ + public static Collection values() { + return values(ChatCompletionExtraParametersBehavior.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormat.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormat.java new file mode 100644 index 000000000000..6eb6c0bb0212 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormat.java @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Determines how the language model's response should be serialized. Defaults to 'text'. + */ +@Fluent +public final class ChatCompletionResponseFormat implements JsonSerializable { + /* + * Specifies how the LLM should format the response. Possible values: 'text' (plain string), 'json_object' + * (arbitrary JSON), or 'json_schema' (adheres to provided schema). + */ + private ChatCompletionResponseFormatType type; + + /* + * An open dictionary for extended properties. Required if 'type' == 'json_schema' + */ + private ChatCompletionResponseFormatJsonSchemaProperties chatCompletionSchemaProperties; + + /** + * Creates an instance of ChatCompletionResponseFormat class. + */ + public ChatCompletionResponseFormat() { + } + + /** + * Get the type property: Specifies how the LLM should format the response. Possible values: 'text' (plain string), + * 'json_object' (arbitrary JSON), or 'json_schema' (adheres to provided schema). + * + * @return the type value. + */ + public ChatCompletionResponseFormatType getType() { + return this.type; + } + + /** + * Set the type property: Specifies how the LLM should format the response. Possible values: 'text' (plain string), + * 'json_object' (arbitrary JSON), or 'json_schema' (adheres to provided schema). + * + * @param type the type value to set. + * @return the ChatCompletionResponseFormat object itself. + */ + public ChatCompletionResponseFormat setType(ChatCompletionResponseFormatType type) { + this.type = type; + return this; + } + + /** + * Get the chatCompletionSchemaProperties property: An open dictionary for extended properties. Required if 'type' + * == 'json_schema'. + * + * @return the chatCompletionSchemaProperties value. + */ + public ChatCompletionResponseFormatJsonSchemaProperties getChatCompletionSchemaProperties() { + return this.chatCompletionSchemaProperties; + } + + /** + * Set the chatCompletionSchemaProperties property: An open dictionary for extended properties. Required if 'type' + * == 'json_schema'. + * + * @param chatCompletionSchemaProperties the chatCompletionSchemaProperties value to set. + * @return the ChatCompletionResponseFormat object itself. + */ + public ChatCompletionResponseFormat setChatCompletionSchemaProperties( + ChatCompletionResponseFormatJsonSchemaProperties chatCompletionSchemaProperties) { + this.chatCompletionSchemaProperties = chatCompletionSchemaProperties; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); + jsonWriter.writeJsonField("jsonSchemaProperties", this.chatCompletionSchemaProperties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionResponseFormat from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionResponseFormat 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 ChatCompletionResponseFormat. + */ + public static ChatCompletionResponseFormat fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionResponseFormat deserializedChatCompletionResponseFormat = new ChatCompletionResponseFormat(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedChatCompletionResponseFormat.type + = ChatCompletionResponseFormatType.fromString(reader.getString()); + } else if ("jsonSchemaProperties".equals(fieldName)) { + deserializedChatCompletionResponseFormat.chatCompletionSchemaProperties + = ChatCompletionResponseFormatJsonSchemaProperties.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedChatCompletionResponseFormat; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormatJsonSchemaProperties.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormatJsonSchemaProperties.java new file mode 100644 index 000000000000..009b59bf3a1d --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormatJsonSchemaProperties.java @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * An open dictionary for extended properties. Required if 'type' == 'json_schema'. + */ +@Fluent +public final class ChatCompletionResponseFormatJsonSchemaProperties + implements JsonSerializable { + /* + * Name of the json schema the model will adhere to + */ + private String name; + + /* + * Description of the json schema the model will adhere to. + */ + private String description; + + /* + * Whether or not the model's response should use structured outputs. Default is true + */ + private Boolean strict; + + /* + * Object defining the custom schema the model will use to structure its output. + */ + private ChatCompletionSchema schema; + + /** + * Creates an instance of ChatCompletionResponseFormatJsonSchemaProperties class. + */ + public ChatCompletionResponseFormatJsonSchemaProperties() { + } + + /** + * Get the name property: Name of the json schema the model will adhere to. + * + * @return the name value. + */ + public String getName() { + return this.name; + } + + /** + * Set the name property: Name of the json schema the model will adhere to. + * + * @param name the name value to set. + * @return the ChatCompletionResponseFormatJsonSchemaProperties object itself. + */ + public ChatCompletionResponseFormatJsonSchemaProperties setName(String name) { + this.name = name; + return this; + } + + /** + * Get the description property: Description of the json schema the model will adhere to. + * + * @return the description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Set the description property: Description of the json schema the model will adhere to. + * + * @param description the description value to set. + * @return the ChatCompletionResponseFormatJsonSchemaProperties object itself. + */ + public ChatCompletionResponseFormatJsonSchemaProperties setDescription(String description) { + this.description = description; + return this; + } + + /** + * Get the strict property: Whether or not the model's response should use structured outputs. Default is true. + * + * @return the strict value. + */ + public Boolean isStrict() { + return this.strict; + } + + /** + * Set the strict property: Whether or not the model's response should use structured outputs. Default is true. + * + * @param strict the strict value to set. + * @return the ChatCompletionResponseFormatJsonSchemaProperties object itself. + */ + public ChatCompletionResponseFormatJsonSchemaProperties setStrict(Boolean strict) { + this.strict = strict; + return this; + } + + /** + * Get the schema property: Object defining the custom schema the model will use to structure its output. + * + * @return the schema value. + */ + public ChatCompletionSchema getSchema() { + return this.schema; + } + + /** + * Set the schema property: Object defining the custom schema the model will use to structure its output. + * + * @param schema the schema value to set. + * @return the ChatCompletionResponseFormatJsonSchemaProperties object itself. + */ + public ChatCompletionResponseFormatJsonSchemaProperties setSchema(ChatCompletionSchema schema) { + this.schema = schema; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("description", this.description); + jsonWriter.writeBooleanField("strict", this.strict); + jsonWriter.writeJsonField("schema", this.schema); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionResponseFormatJsonSchemaProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionResponseFormatJsonSchemaProperties 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 ChatCompletionResponseFormatJsonSchemaProperties. + */ + public static ChatCompletionResponseFormatJsonSchemaProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionResponseFormatJsonSchemaProperties deserializedChatCompletionResponseFormatJsonSchemaProperties + = new ChatCompletionResponseFormatJsonSchemaProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + deserializedChatCompletionResponseFormatJsonSchemaProperties.name = reader.getString(); + } else if ("description".equals(fieldName)) { + deserializedChatCompletionResponseFormatJsonSchemaProperties.description = reader.getString(); + } else if ("strict".equals(fieldName)) { + deserializedChatCompletionResponseFormatJsonSchemaProperties.strict + = reader.getNullable(JsonReader::getBoolean); + } else if ("schema".equals(fieldName)) { + deserializedChatCompletionResponseFormatJsonSchemaProperties.schema + = ChatCompletionSchema.fromJson(reader); + } else { + reader.skipChildren(); + } + } + + return deserializedChatCompletionResponseFormatJsonSchemaProperties; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormatType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormatType.java new file mode 100644 index 000000000000..5e8589cbb9de --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormatType.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Specifies how the LLM should format the response. Possible values: 'text' (plain string), 'json_object' (arbitrary + * JSON), or 'json_schema' (adheres to provided schema). + */ +public final class ChatCompletionResponseFormatType extends ExpandableStringEnum { + /** + * Static value text for ChatCompletionResponseFormatType. + */ + public static final ChatCompletionResponseFormatType TEXT = fromString("text"); + + /** + * Static value jsonObject for ChatCompletionResponseFormatType. + */ + public static final ChatCompletionResponseFormatType JSON_OBJECT = fromString("jsonObject"); + + /** + * Static value jsonSchema for ChatCompletionResponseFormatType. + */ + public static final ChatCompletionResponseFormatType JSON_SCHEMA = fromString("jsonSchema"); + + /** + * Creates a new instance of ChatCompletionResponseFormatType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public ChatCompletionResponseFormatType() { + } + + /** + * Creates or finds a ChatCompletionResponseFormatType from its string representation. + * + * @param name a name to look for. + * @return the corresponding ChatCompletionResponseFormatType. + */ + public static ChatCompletionResponseFormatType fromString(String name) { + return fromString(name, ChatCompletionResponseFormatType.class); + } + + /** + * Gets known ChatCompletionResponseFormatType values. + * + * @return known ChatCompletionResponseFormatType values. + */ + public static Collection values() { + return values(ChatCompletionResponseFormatType.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchema.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchema.java new file mode 100644 index 000000000000..823b5f85fc01 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchema.java @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +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; + +/** + * Object defining the custom schema the model will use to structure its output. + */ +@Fluent +public final class ChatCompletionSchema implements JsonSerializable { + /* + * Type of schema representation. Usually 'object'. Default is 'object'. + */ + private String type; + + /* + * A JSON-formatted string that defines the output schema's properties and constraints for the model. + */ + private String properties; + + /* + * An array of the property names that are required to be part of the model's response. All properties must be + * included for structured outputs. + */ + private List required; + + /* + * Controls whether it is allowable for an object to contain additional keys / values that were not defined in the + * JSON Schema. Default is false. + */ + private Boolean additionalProperties; + + /** + * Creates an instance of ChatCompletionSchema class. + */ + public ChatCompletionSchema() { + } + + /** + * Get the type property: Type of schema representation. Usually 'object'. Default is 'object'. + * + * @return the type value. + */ + public String getType() { + return this.type; + } + + /** + * Set the type property: Type of schema representation. Usually 'object'. Default is 'object'. + * + * @param type the type value to set. + * @return the ChatCompletionSchema object itself. + */ + public ChatCompletionSchema setType(String type) { + this.type = type; + return this; + } + + /** + * Get the properties property: A JSON-formatted string that defines the output schema's properties and constraints + * for the model. + * + * @return the properties value. + */ + public String getProperties() { + return this.properties; + } + + /** + * Set the properties property: A JSON-formatted string that defines the output schema's properties and constraints + * for the model. + * + * @param properties the properties value to set. + * @return the ChatCompletionSchema object itself. + */ + public ChatCompletionSchema setProperties(String properties) { + this.properties = properties; + return this; + } + + /** + * Get the required property: An array of the property names that are required to be part of the model's response. + * All properties must be included for structured outputs. + * + * @return the required value. + */ + public List getRequired() { + return this.required; + } + + /** + * Set the required property: An array of the property names that are required to be part of the model's response. + * All properties must be included for structured outputs. + * + * @param required the required value to set. + * @return the ChatCompletionSchema object itself. + */ + public ChatCompletionSchema setRequired(List required) { + this.required = required; + return this; + } + + /** + * Get the additionalProperties property: Controls whether it is allowable for an object to contain additional keys + * / values that were not defined in the JSON Schema. Default is false. + * + * @return the additionalProperties value. + */ + public Boolean isAdditionalProperties() { + return this.additionalProperties; + } + + /** + * Set the additionalProperties property: Controls whether it is allowable for an object to contain additional keys + * / values that were not defined in the JSON Schema. Default is false. + * + * @param additionalProperties the additionalProperties value to set. + * @return the ChatCompletionSchema object itself. + */ + public ChatCompletionSchema setAdditionalProperties(Boolean additionalProperties) { + this.additionalProperties = additionalProperties; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("properties", this.properties); + jsonWriter.writeArrayField("required", this.required, (writer, element) -> writer.writeString(element)); + jsonWriter.writeBooleanField("additionalProperties", this.additionalProperties); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionSchema from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionSchema 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 ChatCompletionSchema. + */ + public static ChatCompletionSchema fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ChatCompletionSchema deserializedChatCompletionSchema = new ChatCompletionSchema(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("type".equals(fieldName)) { + deserializedChatCompletionSchema.type = reader.getString(); + } else if ("properties".equals(fieldName)) { + deserializedChatCompletionSchema.properties = reader.getString(); + } else if ("required".equals(fieldName)) { + List required = reader.readArray(reader1 -> reader1.getString()); + deserializedChatCompletionSchema.required = required; + } else if ("additionalProperties".equals(fieldName)) { + deserializedChatCompletionSchema.additionalProperties = reader.getNullable(JsonReader::getBoolean); + } else { + reader.skipChildren(); + } + } + + return deserializedChatCompletionSchema; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSkill.java new file mode 100644 index 000000000000..057cd94509d9 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSkill.java @@ -0,0 +1,426 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * A skill that calls a language model via Azure AI Foundry's Chat Completions endpoint. + */ +@Fluent +public final class ChatCompletionSkill extends WebApiSkill { + /* + * A URI fragment specifying the type of skill. + */ + private String odataType = "#Microsoft.Skills.Custom.ChatCompletionSkill"; + + /* + * API key for authenticating to the model. Both apiKey and authIdentity cannot be specified at the same time. + */ + private String apiKey; + + /* + * Common language model parameters that customers can tweak. If omitted, reasonable defaults will be applied. + */ + private CommonModelParameters commonModelParameters; + + /* + * Open-type dictionary for model-specific parameters that should be appended to the chat completions call. Follows + * Azure AI Foundry’s extensibility pattern. + */ + private Map extraParameters; + + /* + * How extra parameters are handled by Azure AI Foundry. Default is 'error'. + */ + private ChatCompletionExtraParametersBehavior extraParametersBehavior; + + /* + * Determines how the LLM should format its response. Defaults to 'text' response type. + */ + private ChatCompletionResponseFormat responseFormat; + + /** + * Creates an instance of ChatCompletionSkill class. + * + * @param inputs the inputs value to set. + * @param outputs the outputs value to set. + * @param uri the uri value to set. + */ + public ChatCompletionSkill(List inputs, List outputs, String uri) { + super(inputs, outputs, uri); + } + + /** + * Get the odataType property: A URI fragment specifying the type of skill. + * + * @return the odataType value. + */ + @Override + public String getOdataType() { + return this.odataType; + } + + /** + * Get the apiKey property: API key for authenticating to the model. Both apiKey and authIdentity cannot be + * specified at the same time. + * + * @return the apiKey value. + */ + public String getApiKey() { + return this.apiKey; + } + + /** + * Set the apiKey property: API key for authenticating to the model. Both apiKey and authIdentity cannot be + * specified at the same time. + * + * @param apiKey the apiKey value to set. + * @return the ChatCompletionSkill object itself. + */ + public ChatCompletionSkill setApiKey(String apiKey) { + this.apiKey = apiKey; + return this; + } + + /** + * Get the commonModelParameters property: Common language model parameters that customers can tweak. If omitted, + * reasonable defaults will be applied. + * + * @return the commonModelParameters value. + */ + public CommonModelParameters getCommonModelParameters() { + return this.commonModelParameters; + } + + /** + * Set the commonModelParameters property: Common language model parameters that customers can tweak. If omitted, + * reasonable defaults will be applied. + * + * @param commonModelParameters the commonModelParameters value to set. + * @return the ChatCompletionSkill object itself. + */ + public ChatCompletionSkill setCommonModelParameters(CommonModelParameters commonModelParameters) { + this.commonModelParameters = commonModelParameters; + return this; + } + + /** + * Get the extraParameters property: Open-type dictionary for model-specific parameters that should be appended to + * the chat completions call. Follows Azure AI Foundry’s extensibility pattern. + * + * @return the extraParameters value. + */ + public Map getExtraParameters() { + return this.extraParameters; + } + + /** + * Set the extraParameters property: Open-type dictionary for model-specific parameters that should be appended to + * the chat completions call. Follows Azure AI Foundry’s extensibility pattern. + * + * @param extraParameters the extraParameters value to set. + * @return the ChatCompletionSkill object itself. + */ + public ChatCompletionSkill setExtraParameters(Map extraParameters) { + this.extraParameters = extraParameters; + return this; + } + + /** + * Get the extraParametersBehavior property: How extra parameters are handled by Azure AI Foundry. Default is + * 'error'. + * + * @return the extraParametersBehavior value. + */ + public ChatCompletionExtraParametersBehavior getExtraParametersBehavior() { + return this.extraParametersBehavior; + } + + /** + * Set the extraParametersBehavior property: How extra parameters are handled by Azure AI Foundry. Default is + * 'error'. + * + * @param extraParametersBehavior the extraParametersBehavior value to set. + * @return the ChatCompletionSkill object itself. + */ + public ChatCompletionSkill + setExtraParametersBehavior(ChatCompletionExtraParametersBehavior extraParametersBehavior) { + this.extraParametersBehavior = extraParametersBehavior; + return this; + } + + /** + * Get the responseFormat property: Determines how the LLM should format its response. Defaults to 'text' response + * type. + * + * @return the responseFormat value. + */ + public ChatCompletionResponseFormat getResponseFormat() { + return this.responseFormat; + } + + /** + * Set the responseFormat property: Determines how the LLM should format its response. Defaults to 'text' response + * type. + * + * @param responseFormat the responseFormat value to set. + * @return the ChatCompletionSkill object itself. + */ + public ChatCompletionSkill setResponseFormat(ChatCompletionResponseFormat responseFormat) { + this.responseFormat = responseFormat; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ChatCompletionSkill setHttpHeaders(Map httpHeaders) { + super.setHttpHeaders(httpHeaders); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ChatCompletionSkill setHttpMethod(String httpMethod) { + super.setHttpMethod(httpMethod); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ChatCompletionSkill setTimeout(Duration timeout) { + super.setTimeout(timeout); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ChatCompletionSkill setBatchSize(Integer batchSize) { + super.setBatchSize(batchSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ChatCompletionSkill setDegreeOfParallelism(Integer degreeOfParallelism) { + super.setDegreeOfParallelism(degreeOfParallelism); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ChatCompletionSkill setAuthResourceId(String authResourceId) { + super.setAuthResourceId(authResourceId); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ChatCompletionSkill setAuthIdentity(SearchIndexerDataIdentity authIdentity) { + super.setAuthIdentity(authIdentity); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ChatCompletionSkill setName(String name) { + super.setName(name); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ChatCompletionSkill setDescription(String description) { + super.setDescription(description); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ChatCompletionSkill setContext(String context) { + super.setContext(context); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("inputs", getInputs(), (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("outputs", getOutputs(), (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("uri", getUri()); + jsonWriter.writeStringField("name", getName()); + jsonWriter.writeStringField("description", getDescription()); + jsonWriter.writeStringField("context", getContext()); + jsonWriter.writeMapField("httpHeaders", getHttpHeaders(), (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("httpMethod", getHttpMethod()); + jsonWriter.writeStringField("timeout", CoreUtils.durationToStringWithDays(getTimeout())); + jsonWriter.writeNumberField("batchSize", getBatchSize()); + jsonWriter.writeNumberField("degreeOfParallelism", getDegreeOfParallelism()); + jsonWriter.writeStringField("authResourceId", getAuthResourceId()); + jsonWriter.writeJsonField("authIdentity", getAuthIdentity()); + jsonWriter.writeStringField("@odata.type", this.odataType); + jsonWriter.writeStringField("apiKey", this.apiKey); + jsonWriter.writeJsonField("commonModelParameters", this.commonModelParameters); + jsonWriter.writeMapField("extraParameters", this.extraParameters, + (writer, element) -> writer.writeUntyped(element)); + jsonWriter.writeStringField("extraParametersBehavior", + this.extraParametersBehavior == null ? null : this.extraParametersBehavior.toString()); + jsonWriter.writeJsonField("responseFormat", this.responseFormat); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ChatCompletionSkill from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ChatCompletionSkill 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 ChatCompletionSkill. + */ + public static ChatCompletionSkill fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean inputsFound = false; + List inputs = null; + boolean outputsFound = false; + List outputs = null; + boolean uriFound = false; + String uri = null; + String name = null; + String description = null; + String context = null; + Map httpHeaders = null; + String httpMethod = null; + Duration timeout = null; + Integer batchSize = null; + Integer degreeOfParallelism = null; + String authResourceId = null; + SearchIndexerDataIdentity authIdentity = null; + String odataType = "#Microsoft.Skills.Custom.ChatCompletionSkill"; + String apiKey = null; + CommonModelParameters commonModelParameters = null; + Map extraParameters = null; + ChatCompletionExtraParametersBehavior extraParametersBehavior = null; + ChatCompletionResponseFormat responseFormat = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("inputs".equals(fieldName)) { + inputs = reader.readArray(reader1 -> InputFieldMappingEntry.fromJson(reader1)); + inputsFound = true; + } else if ("outputs".equals(fieldName)) { + outputs = reader.readArray(reader1 -> OutputFieldMappingEntry.fromJson(reader1)); + outputsFound = true; + } else if ("uri".equals(fieldName)) { + uri = reader.getString(); + uriFound = true; + } else if ("name".equals(fieldName)) { + name = reader.getString(); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else if ("context".equals(fieldName)) { + context = reader.getString(); + } else if ("httpHeaders".equals(fieldName)) { + httpHeaders = reader.readMap(reader1 -> reader1.getString()); + } else if ("httpMethod".equals(fieldName)) { + httpMethod = reader.getString(); + } else if ("timeout".equals(fieldName)) { + timeout = reader.getNullable(nonNullReader -> Duration.parse(nonNullReader.getString())); + } else if ("batchSize".equals(fieldName)) { + batchSize = reader.getNullable(JsonReader::getInt); + } else if ("degreeOfParallelism".equals(fieldName)) { + degreeOfParallelism = reader.getNullable(JsonReader::getInt); + } else if ("authResourceId".equals(fieldName)) { + authResourceId = reader.getString(); + } else if ("authIdentity".equals(fieldName)) { + authIdentity = SearchIndexerDataIdentity.fromJson(reader); + } else if ("@odata.type".equals(fieldName)) { + odataType = reader.getString(); + } else if ("apiKey".equals(fieldName)) { + apiKey = reader.getString(); + } else if ("commonModelParameters".equals(fieldName)) { + commonModelParameters = CommonModelParameters.fromJson(reader); + } else if ("extraParameters".equals(fieldName)) { + extraParameters = reader.readMap(reader1 -> reader1.readUntyped()); + } else if ("extraParametersBehavior".equals(fieldName)) { + extraParametersBehavior = ChatCompletionExtraParametersBehavior.fromString(reader.getString()); + } else if ("responseFormat".equals(fieldName)) { + responseFormat = ChatCompletionResponseFormat.fromJson(reader); + } else { + reader.skipChildren(); + } + } + if (inputsFound && outputsFound && uriFound) { + ChatCompletionSkill deserializedChatCompletionSkill = new ChatCompletionSkill(inputs, outputs, uri); + deserializedChatCompletionSkill.setName(name); + deserializedChatCompletionSkill.setDescription(description); + deserializedChatCompletionSkill.setContext(context); + deserializedChatCompletionSkill.setHttpHeaders(httpHeaders); + deserializedChatCompletionSkill.setHttpMethod(httpMethod); + deserializedChatCompletionSkill.setTimeout(timeout); + deserializedChatCompletionSkill.setBatchSize(batchSize); + deserializedChatCompletionSkill.setDegreeOfParallelism(degreeOfParallelism); + deserializedChatCompletionSkill.setAuthResourceId(authResourceId); + deserializedChatCompletionSkill.setAuthIdentity(authIdentity); + deserializedChatCompletionSkill.odataType = odataType; + deserializedChatCompletionSkill.apiKey = apiKey; + deserializedChatCompletionSkill.commonModelParameters = commonModelParameters; + deserializedChatCompletionSkill.extraParameters = extraParameters; + deserializedChatCompletionSkill.extraParametersBehavior = extraParametersBehavior; + deserializedChatCompletionSkill.responseFormat = responseFormat; + + return deserializedChatCompletionSkill; + } + List missingProperties = new ArrayList<>(); + if (!inputsFound) { + missingProperties.add("inputs"); + } + if (!outputsFound) { + missingProperties.add("outputs"); + } + if (!uriFound) { + missingProperties.add("uri"); + } + + throw new IllegalStateException( + "Missing required property/properties: " + String.join(", ", missingProperties)); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CommonModelParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CommonModelParameters.java new file mode 100644 index 000000000000..636fd96f44a0 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CommonModelParameters.java @@ -0,0 +1,261 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +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; + +/** + * Common language model parameters for Chat Completions. If omitted, default values are used. + */ +@Fluent +public final class CommonModelParameters implements JsonSerializable { + /* + * The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not specified. + */ + private String model; + + /* + * A float in the range [-2,2] that reduces or increases likelihood of repeated tokens. Default is 0. + */ + private Float frequencyPenalty; + + /* + * A float in the range [-2,2] that penalizes new tokens based on their existing presence. Default is 0. + */ + private Float presencePenalty; + + /* + * Maximum number of tokens to generate. + */ + private Integer maxTokens; + + /* + * Sampling temperature. Default is 0.7. + */ + private Float temperature; + + /* + * Random seed for controlling deterministic outputs. If omitted, randomization is used. + */ + private Integer seed; + + /* + * List of stop sequences that will cut off text generation. Default is none. + */ + private List stop; + + /** + * Creates an instance of CommonModelParameters class. + */ + public CommonModelParameters() { + } + + /** + * Get the model property: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not specified. + * + * @return the model value. + */ + public String getModel() { + return this.model; + } + + /** + * Set the model property: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not specified. + * + * @param model the model value to set. + * @return the CommonModelParameters object itself. + */ + public CommonModelParameters setModel(String model) { + this.model = model; + return this; + } + + /** + * Get the frequencyPenalty property: A float in the range [-2,2] that reduces or increases likelihood of repeated + * tokens. Default is 0. + * + * @return the frequencyPenalty value. + */ + public Float getFrequencyPenalty() { + return this.frequencyPenalty; + } + + /** + * Set the frequencyPenalty property: A float in the range [-2,2] that reduces or increases likelihood of repeated + * tokens. Default is 0. + * + * @param frequencyPenalty the frequencyPenalty value to set. + * @return the CommonModelParameters object itself. + */ + public CommonModelParameters setFrequencyPenalty(Float frequencyPenalty) { + this.frequencyPenalty = frequencyPenalty; + return this; + } + + /** + * Get the presencePenalty property: A float in the range [-2,2] that penalizes new tokens based on their existing + * presence. Default is 0. + * + * @return the presencePenalty value. + */ + public Float getPresencePenalty() { + return this.presencePenalty; + } + + /** + * Set the presencePenalty property: A float in the range [-2,2] that penalizes new tokens based on their existing + * presence. Default is 0. + * + * @param presencePenalty the presencePenalty value to set. + * @return the CommonModelParameters object itself. + */ + public CommonModelParameters setPresencePenalty(Float presencePenalty) { + this.presencePenalty = presencePenalty; + return this; + } + + /** + * Get the maxTokens property: Maximum number of tokens to generate. + * + * @return the maxTokens value. + */ + public Integer getMaxTokens() { + return this.maxTokens; + } + + /** + * Set the maxTokens property: Maximum number of tokens to generate. + * + * @param maxTokens the maxTokens value to set. + * @return the CommonModelParameters object itself. + */ + public CommonModelParameters setMaxTokens(Integer maxTokens) { + this.maxTokens = maxTokens; + return this; + } + + /** + * Get the temperature property: Sampling temperature. Default is 0.7. + * + * @return the temperature value. + */ + public Float getTemperature() { + return this.temperature; + } + + /** + * Set the temperature property: Sampling temperature. Default is 0.7. + * + * @param temperature the temperature value to set. + * @return the CommonModelParameters object itself. + */ + public CommonModelParameters setTemperature(Float temperature) { + this.temperature = temperature; + return this; + } + + /** + * Get the seed property: Random seed for controlling deterministic outputs. If omitted, randomization is used. + * + * @return the seed value. + */ + public Integer getSeed() { + return this.seed; + } + + /** + * Set the seed property: Random seed for controlling deterministic outputs. If omitted, randomization is used. + * + * @param seed the seed value to set. + * @return the CommonModelParameters object itself. + */ + public CommonModelParameters setSeed(Integer seed) { + this.seed = seed; + return this; + } + + /** + * Get the stop property: List of stop sequences that will cut off text generation. Default is none. + * + * @return the stop value. + */ + public List getStop() { + return this.stop; + } + + /** + * Set the stop property: List of stop sequences that will cut off text generation. Default is none. + * + * @param stop the stop value to set. + * @return the CommonModelParameters object itself. + */ + public CommonModelParameters setStop(List stop) { + this.stop = stop; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("model", this.model); + jsonWriter.writeNumberField("frequencyPenalty", this.frequencyPenalty); + jsonWriter.writeNumberField("presencePenalty", this.presencePenalty); + jsonWriter.writeNumberField("maxTokens", this.maxTokens); + jsonWriter.writeNumberField("temperature", this.temperature); + jsonWriter.writeNumberField("seed", this.seed); + jsonWriter.writeArrayField("stop", this.stop, (writer, element) -> writer.writeString(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CommonModelParameters from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CommonModelParameters 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 CommonModelParameters. + */ + public static CommonModelParameters fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CommonModelParameters deserializedCommonModelParameters = new CommonModelParameters(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("model".equals(fieldName)) { + deserializedCommonModelParameters.model = reader.getString(); + } else if ("frequencyPenalty".equals(fieldName)) { + deserializedCommonModelParameters.frequencyPenalty = reader.getNullable(JsonReader::getFloat); + } else if ("presencePenalty".equals(fieldName)) { + deserializedCommonModelParameters.presencePenalty = reader.getNullable(JsonReader::getFloat); + } else if ("maxTokens".equals(fieldName)) { + deserializedCommonModelParameters.maxTokens = reader.getNullable(JsonReader::getInt); + } else if ("temperature".equals(fieldName)) { + deserializedCommonModelParameters.temperature = reader.getNullable(JsonReader::getFloat); + } else if ("seed".equals(fieldName)) { + deserializedCommonModelParameters.seed = reader.getNullable(JsonReader::getInt); + } else if ("stop".equals(fieldName)) { + List stop = reader.readArray(reader1 -> reader1.getString()); + deserializedCommonModelParameters.stop = stop; + } else { + reader.skipChildren(); + } + } + + return deserializedCommonModelParameters; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkill.java index 6e9984b142ed..fe5b06b0ea97 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkill.java @@ -15,8 +15,8 @@ import java.util.List; /** - * A skill that extracts content and layout information (as markdown), via Azure AI Services, from files within the - * enrichment pipeline. + * A skill that extracts content and layout information, via Azure AI Services, from files within the enrichment + * pipeline. */ @Fluent public final class DocumentIntelligenceLayoutSkill extends SearchIndexerSkill { @@ -25,6 +25,11 @@ public final class DocumentIntelligenceLayoutSkill extends SearchIndexerSkill { */ private String odataType = "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill"; + /* + * Controls the cardinality of the output format. Default is 'markdown'. + */ + private DocumentIntelligenceLayoutSkillOutputFormat outputFormat; + /* * Controls the cardinality of the output produced by the skill. Default is 'oneToMany'. */ @@ -35,6 +40,16 @@ public final class DocumentIntelligenceLayoutSkill extends SearchIndexerSkill { */ private DocumentIntelligenceLayoutSkillMarkdownHeaderDepth markdownHeaderDepth; + /* + * Controls the cardinality of the content extracted from the document by the skill + */ + private List extractionOptions; + + /* + * Controls the cardinality for chunking the content. + */ + private DocumentIntelligenceLayoutSkillChunkingProperties chunkingProperties; + /** * Creates an instance of DocumentIntelligenceLayoutSkill class. * @@ -55,6 +70,26 @@ public String getOdataType() { return this.odataType; } + /** + * Get the outputFormat property: Controls the cardinality of the output format. Default is 'markdown'. + * + * @return the outputFormat value. + */ + public DocumentIntelligenceLayoutSkillOutputFormat getOutputFormat() { + return this.outputFormat; + } + + /** + * Set the outputFormat property: Controls the cardinality of the output format. Default is 'markdown'. + * + * @param outputFormat the outputFormat value to set. + * @return the DocumentIntelligenceLayoutSkill object itself. + */ + public DocumentIntelligenceLayoutSkill setOutputFormat(DocumentIntelligenceLayoutSkillOutputFormat outputFormat) { + this.outputFormat = outputFormat; + return this; + } + /** * Get the outputMode property: Controls the cardinality of the output produced by the skill. Default is * 'oneToMany'. @@ -98,6 +133,50 @@ public DocumentIntelligenceLayoutSkillMarkdownHeaderDepth getMarkdownHeaderDepth return this; } + /** + * Get the extractionOptions property: Controls the cardinality of the content extracted from the document by the + * skill. + * + * @return the extractionOptions value. + */ + public List getExtractionOptions() { + return this.extractionOptions; + } + + /** + * Set the extractionOptions property: Controls the cardinality of the content extracted from the document by the + * skill. + * + * @param extractionOptions the extractionOptions value to set. + * @return the DocumentIntelligenceLayoutSkill object itself. + */ + public DocumentIntelligenceLayoutSkill + setExtractionOptions(List extractionOptions) { + this.extractionOptions = extractionOptions; + return this; + } + + /** + * Get the chunkingProperties property: Controls the cardinality for chunking the content. + * + * @return the chunkingProperties value. + */ + public DocumentIntelligenceLayoutSkillChunkingProperties getChunkingProperties() { + return this.chunkingProperties; + } + + /** + * Set the chunkingProperties property: Controls the cardinality for chunking the content. + * + * @param chunkingProperties the chunkingProperties value to set. + * @return the DocumentIntelligenceLayoutSkill object itself. + */ + public DocumentIntelligenceLayoutSkill + setChunkingProperties(DocumentIntelligenceLayoutSkillChunkingProperties chunkingProperties) { + this.chunkingProperties = chunkingProperties; + return this; + } + /** * {@inheritDoc} */ @@ -137,9 +216,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeStringField("context", getContext()); jsonWriter.writeStringField("@odata.type", this.odataType); + jsonWriter.writeStringField("outputFormat", this.outputFormat == null ? null : this.outputFormat.toString()); jsonWriter.writeStringField("outputMode", this.outputMode == null ? null : this.outputMode.toString()); jsonWriter.writeStringField("markdownHeaderDepth", this.markdownHeaderDepth == null ? null : this.markdownHeaderDepth.toString()); + jsonWriter.writeArrayField("extractionOptions", this.extractionOptions, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeJsonField("chunkingProperties", this.chunkingProperties); return jsonWriter.writeEndObject(); } @@ -162,8 +245,11 @@ public static DocumentIntelligenceLayoutSkill fromJson(JsonReader jsonReader) th String description = null; String context = null; String odataType = "#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill"; + DocumentIntelligenceLayoutSkillOutputFormat outputFormat = null; DocumentIntelligenceLayoutSkillOutputMode outputMode = null; DocumentIntelligenceLayoutSkillMarkdownHeaderDepth markdownHeaderDepth = null; + List extractionOptions = null; + DocumentIntelligenceLayoutSkillChunkingProperties chunkingProperties = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); @@ -182,11 +268,18 @@ public static DocumentIntelligenceLayoutSkill fromJson(JsonReader jsonReader) th context = reader.getString(); } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); + } else if ("outputFormat".equals(fieldName)) { + outputFormat = DocumentIntelligenceLayoutSkillOutputFormat.fromString(reader.getString()); } else if ("outputMode".equals(fieldName)) { outputMode = DocumentIntelligenceLayoutSkillOutputMode.fromString(reader.getString()); } else if ("markdownHeaderDepth".equals(fieldName)) { markdownHeaderDepth = DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.fromString(reader.getString()); + } else if ("extractionOptions".equals(fieldName)) { + extractionOptions = reader.readArray( + reader1 -> DocumentIntelligenceLayoutSkillExtractionOptions.fromString(reader1.getString())); + } else if ("chunkingProperties".equals(fieldName)) { + chunkingProperties = DocumentIntelligenceLayoutSkillChunkingProperties.fromJson(reader); } else { reader.skipChildren(); } @@ -198,8 +291,11 @@ public static DocumentIntelligenceLayoutSkill fromJson(JsonReader jsonReader) th deserializedDocumentIntelligenceLayoutSkill.setDescription(description); deserializedDocumentIntelligenceLayoutSkill.setContext(context); deserializedDocumentIntelligenceLayoutSkill.odataType = odataType; + deserializedDocumentIntelligenceLayoutSkill.outputFormat = outputFormat; deserializedDocumentIntelligenceLayoutSkill.outputMode = outputMode; deserializedDocumentIntelligenceLayoutSkill.markdownHeaderDepth = markdownHeaderDepth; + deserializedDocumentIntelligenceLayoutSkill.extractionOptions = extractionOptions; + deserializedDocumentIntelligenceLayoutSkill.chunkingProperties = chunkingProperties; return deserializedDocumentIntelligenceLayoutSkill; } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingProperties.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingProperties.java new file mode 100644 index 000000000000..795d71ef8088 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingProperties.java @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Controls the cardinality for chunking the content. + */ +@Fluent +public final class DocumentIntelligenceLayoutSkillChunkingProperties + implements JsonSerializable { + /* + * The unit of the chunk. + */ + private DocumentIntelligenceLayoutSkillChunkingUnit unit; + + /* + * The maximum chunk length in characters. Default is 500. + */ + private Integer maximumLength; + + /* + * The length of overlap provided between two text chunks. Default is 0. + */ + private Integer overlapLength; + + /** + * Creates an instance of DocumentIntelligenceLayoutSkillChunkingProperties class. + */ + public DocumentIntelligenceLayoutSkillChunkingProperties() { + } + + /** + * Get the unit property: The unit of the chunk. + * + * @return the unit value. + */ + public DocumentIntelligenceLayoutSkillChunkingUnit getUnit() { + return this.unit; + } + + /** + * Set the unit property: The unit of the chunk. + * + * @param unit the unit value to set. + * @return the DocumentIntelligenceLayoutSkillChunkingProperties object itself. + */ + public DocumentIntelligenceLayoutSkillChunkingProperties setUnit(DocumentIntelligenceLayoutSkillChunkingUnit unit) { + this.unit = unit; + return this; + } + + /** + * Get the maximumLength property: The maximum chunk length in characters. Default is 500. + * + * @return the maximumLength value. + */ + public Integer getMaximumLength() { + return this.maximumLength; + } + + /** + * Set the maximumLength property: The maximum chunk length in characters. Default is 500. + * + * @param maximumLength the maximumLength value to set. + * @return the DocumentIntelligenceLayoutSkillChunkingProperties object itself. + */ + public DocumentIntelligenceLayoutSkillChunkingProperties setMaximumLength(Integer maximumLength) { + this.maximumLength = maximumLength; + return this; + } + + /** + * Get the overlapLength property: The length of overlap provided between two text chunks. Default is 0. + * + * @return the overlapLength value. + */ + public Integer getOverlapLength() { + return this.overlapLength; + } + + /** + * Set the overlapLength property: The length of overlap provided between two text chunks. Default is 0. + * + * @param overlapLength the overlapLength value to set. + * @return the DocumentIntelligenceLayoutSkillChunkingProperties object itself. + */ + public DocumentIntelligenceLayoutSkillChunkingProperties setOverlapLength(Integer overlapLength) { + this.overlapLength = overlapLength; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("unit", this.unit == null ? null : this.unit.toString()); + jsonWriter.writeNumberField("maximumLength", this.maximumLength); + jsonWriter.writeNumberField("overlapLength", this.overlapLength); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of DocumentIntelligenceLayoutSkillChunkingProperties from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of DocumentIntelligenceLayoutSkillChunkingProperties 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 DocumentIntelligenceLayoutSkillChunkingProperties. + */ + public static DocumentIntelligenceLayoutSkillChunkingProperties fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + DocumentIntelligenceLayoutSkillChunkingProperties deserializedDocumentIntelligenceLayoutSkillChunkingProperties + = new DocumentIntelligenceLayoutSkillChunkingProperties(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("unit".equals(fieldName)) { + deserializedDocumentIntelligenceLayoutSkillChunkingProperties.unit + = DocumentIntelligenceLayoutSkillChunkingUnit.fromString(reader.getString()); + } else if ("maximumLength".equals(fieldName)) { + deserializedDocumentIntelligenceLayoutSkillChunkingProperties.maximumLength + = reader.getNullable(JsonReader::getInt); + } else if ("overlapLength".equals(fieldName)) { + deserializedDocumentIntelligenceLayoutSkillChunkingProperties.overlapLength + = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedDocumentIntelligenceLayoutSkillChunkingProperties; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingUnit.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingUnit.java new file mode 100644 index 000000000000..a48bbf970749 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingUnit.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Controls the cardinality of the chunk unit. Default is 'characters'. + */ +public final class DocumentIntelligenceLayoutSkillChunkingUnit + extends ExpandableStringEnum { + /** + * Specifies chunk by characters. + */ + public static final DocumentIntelligenceLayoutSkillChunkingUnit CHARACTERS = fromString("characters"); + + /** + * Creates a new instance of DocumentIntelligenceLayoutSkillChunkingUnit value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public DocumentIntelligenceLayoutSkillChunkingUnit() { + } + + /** + * Creates or finds a DocumentIntelligenceLayoutSkillChunkingUnit from its string representation. + * + * @param name a name to look for. + * @return the corresponding DocumentIntelligenceLayoutSkillChunkingUnit. + */ + public static DocumentIntelligenceLayoutSkillChunkingUnit fromString(String name) { + return fromString(name, DocumentIntelligenceLayoutSkillChunkingUnit.class); + } + + /** + * Gets known DocumentIntelligenceLayoutSkillChunkingUnit values. + * + * @return known DocumentIntelligenceLayoutSkillChunkingUnit values. + */ + public static Collection values() { + return values(DocumentIntelligenceLayoutSkillChunkingUnit.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillExtractionOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillExtractionOptions.java new file mode 100644 index 000000000000..c431fac1a39e --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillExtractionOptions.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Controls the cardinality of the content extracted from the document by the skill. + */ +public final class DocumentIntelligenceLayoutSkillExtractionOptions + extends ExpandableStringEnum { + /** + * Specify that image content should be extracted from the document. + */ + public static final DocumentIntelligenceLayoutSkillExtractionOptions IMAGES = fromString("images"); + + /** + * Specify that location metadata should be extracted from the document. + */ + public static final DocumentIntelligenceLayoutSkillExtractionOptions LOCATION_METADATA + = fromString("locationMetadata"); + + /** + * Creates a new instance of DocumentIntelligenceLayoutSkillExtractionOptions value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public DocumentIntelligenceLayoutSkillExtractionOptions() { + } + + /** + * Creates or finds a DocumentIntelligenceLayoutSkillExtractionOptions from its string representation. + * + * @param name a name to look for. + * @return the corresponding DocumentIntelligenceLayoutSkillExtractionOptions. + */ + public static DocumentIntelligenceLayoutSkillExtractionOptions fromString(String name) { + return fromString(name, DocumentIntelligenceLayoutSkillExtractionOptions.class); + } + + /** + * Gets known DocumentIntelligenceLayoutSkillExtractionOptions values. + * + * @return known DocumentIntelligenceLayoutSkillExtractionOptions values. + */ + public static Collection values() { + return values(DocumentIntelligenceLayoutSkillExtractionOptions.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputFormat.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputFormat.java new file mode 100644 index 000000000000..d6a1b7d81270 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputFormat.java @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Controls the cardinality of the output format. Default is 'markdown'. + */ +public final class DocumentIntelligenceLayoutSkillOutputFormat + extends ExpandableStringEnum { + /** + * Specify the format of the output as text. + */ + public static final DocumentIntelligenceLayoutSkillOutputFormat TEXT = fromString("text"); + + /** + * Specify the format of the output as markdown. + */ + public static final DocumentIntelligenceLayoutSkillOutputFormat MARKDOWN = fromString("markdown"); + + /** + * Creates a new instance of DocumentIntelligenceLayoutSkillOutputFormat value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public DocumentIntelligenceLayoutSkillOutputFormat() { + } + + /** + * Creates or finds a DocumentIntelligenceLayoutSkillOutputFormat from its string representation. + * + * @param name a name to look for. + * @return the corresponding DocumentIntelligenceLayoutSkillOutputFormat. + */ + public static DocumentIntelligenceLayoutSkillOutputFormat fromString(String name) { + return fromString(name, DocumentIntelligenceLayoutSkillOutputFormat.class); + } + + /** + * Gets known DocumentIntelligenceLayoutSkillOutputFormat values. + * + * @return known DocumentIntelligenceLayoutSkillOutputFormat values. + */ + public static Collection values() { + return values(DocumentIntelligenceLayoutSkillOutputFormat.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputMode.java index 1bd1fe113b19..44d1651d51b5 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputMode.java @@ -15,7 +15,7 @@ public final class DocumentIntelligenceLayoutSkillOutputMode extends ExpandableStringEnum { /** - * Specify the deepest markdown header section to parse. + * Specify that the output should be parsed as 'oneToMany'. */ public static final DocumentIntelligenceLayoutSkillOutputMode ONE_TO_MANY = fromString("oneToMany"); diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerCurrentState.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerCurrentState.java index b88db42a19d6..f0b3d76ed0cc 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerCurrentState.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerCurrentState.java @@ -27,22 +27,22 @@ public final class IndexerCurrentState implements JsonSerializable resetDatasourceDocumentIds; + /* + * Change tracking state used when indexing starts on selective options from the datasource. + */ + private String resyncInitialTrackingState; + + /* + * Change tracking state value when indexing finishes on selective options from the datasource. + */ + private String resyncFinalTrackingState; + /** * Creates an instance of IndexerCurrentState class. */ @@ -72,43 +82,43 @@ public IndexingMode getMode() { } /** - * Get the allDocsInitialChangeTrackingState property: Change tracking state used when indexing starts on all - * documents in the datasource. + * Get the allDocsInitialTrackingState property: Change tracking state used when indexing starts on all documents in + * the datasource. * - * @return the allDocsInitialChangeTrackingState value. + * @return the allDocsInitialTrackingState value. */ - public String getAllDocsInitialChangeTrackingState() { - return this.allDocsInitialChangeTrackingState; + public String getAllDocsInitialTrackingState() { + return this.allDocsInitialTrackingState; } /** - * Get the allDocsFinalChangeTrackingState property: Change tracking state value when indexing finishes on all - * documents in the datasource. + * Get the allDocsFinalTrackingState property: Change tracking state value when indexing finishes on all documents + * in the datasource. * - * @return the allDocsFinalChangeTrackingState value. + * @return the allDocsFinalTrackingState value. */ - public String getAllDocsFinalChangeTrackingState() { - return this.allDocsFinalChangeTrackingState; + public String getAllDocsFinalTrackingState() { + return this.allDocsFinalTrackingState; } /** - * Get the resetDocsInitialChangeTrackingState property: Change tracking state used when indexing starts on select, - * reset documents in the datasource. + * Get the resetDocsInitialTrackingState property: Change tracking state used when indexing starts on select, reset + * documents in the datasource. * - * @return the resetDocsInitialChangeTrackingState value. + * @return the resetDocsInitialTrackingState value. */ - public String getResetDocsInitialChangeTrackingState() { - return this.resetDocsInitialChangeTrackingState; + public String getResetDocsInitialTrackingState() { + return this.resetDocsInitialTrackingState; } /** - * Get the resetDocsFinalChangeTrackingState property: Change tracking state value when indexing finishes on select, - * reset documents in the datasource. + * Get the resetDocsFinalTrackingState property: Change tracking state value when indexing finishes on select, reset + * documents in the datasource. * - * @return the resetDocsFinalChangeTrackingState value. + * @return the resetDocsFinalTrackingState value. */ - public String getResetDocsFinalChangeTrackingState() { - return this.resetDocsFinalChangeTrackingState; + public String getResetDocsFinalTrackingState() { + return this.resetDocsFinalTrackingState; } /** @@ -133,6 +143,26 @@ public List getResetDatasourceDocumentIds() { return this.resetDatasourceDocumentIds; } + /** + * Get the resyncInitialTrackingState property: Change tracking state used when indexing starts on selective options + * from the datasource. + * + * @return the resyncInitialTrackingState value. + */ + public String getResyncInitialTrackingState() { + return this.resyncInitialTrackingState; + } + + /** + * Get the resyncFinalTrackingState property: Change tracking state value when indexing finishes on selective + * options from the datasource. + * + * @return the resyncFinalTrackingState value. + */ + public String getResyncFinalTrackingState() { + return this.resyncFinalTrackingState; + } + /** * {@inheritDoc} */ @@ -159,20 +189,24 @@ public static IndexerCurrentState fromJson(JsonReader jsonReader) throws IOExcep if ("mode".equals(fieldName)) { deserializedIndexerCurrentState.mode = IndexingMode.fromString(reader.getString()); - } else if ("allDocsInitialChangeTrackingState".equals(fieldName)) { - deserializedIndexerCurrentState.allDocsInitialChangeTrackingState = reader.getString(); - } else if ("allDocsFinalChangeTrackingState".equals(fieldName)) { - deserializedIndexerCurrentState.allDocsFinalChangeTrackingState = reader.getString(); - } else if ("resetDocsInitialChangeTrackingState".equals(fieldName)) { - deserializedIndexerCurrentState.resetDocsInitialChangeTrackingState = reader.getString(); - } else if ("resetDocsFinalChangeTrackingState".equals(fieldName)) { - deserializedIndexerCurrentState.resetDocsFinalChangeTrackingState = reader.getString(); + } else if ("allDocsInitialTrackingState".equals(fieldName)) { + deserializedIndexerCurrentState.allDocsInitialTrackingState = reader.getString(); + } else if ("allDocsFinalTrackingState".equals(fieldName)) { + deserializedIndexerCurrentState.allDocsFinalTrackingState = reader.getString(); + } else if ("resetDocsInitialTrackingState".equals(fieldName)) { + deserializedIndexerCurrentState.resetDocsInitialTrackingState = reader.getString(); + } else if ("resetDocsFinalTrackingState".equals(fieldName)) { + deserializedIndexerCurrentState.resetDocsFinalTrackingState = reader.getString(); } else if ("resetDocumentKeys".equals(fieldName)) { List resetDocumentKeys = reader.readArray(reader1 -> reader1.getString()); deserializedIndexerCurrentState.resetDocumentKeys = resetDocumentKeys; } else if ("resetDatasourceDocumentIds".equals(fieldName)) { List resetDatasourceDocumentIds = reader.readArray(reader1 -> reader1.getString()); deserializedIndexerCurrentState.resetDatasourceDocumentIds = resetDatasourceDocumentIds; + } else if ("resyncInitialTrackingState".equals(fieldName)) { + deserializedIndexerCurrentState.resyncInitialTrackingState = reader.getString(); + } else if ("resyncFinalTrackingState".equals(fieldName)) { + deserializedIndexerCurrentState.resyncFinalTrackingState = reader.getString(); } else { reader.skipChildren(); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionResult.java index 66bf3a8b1a3f..41251de074a8 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionResult.java @@ -33,9 +33,9 @@ public final class IndexerExecutionResult implements JsonSerializable { + /** + * Indexer to ingest ACL userIds from data source to index. + */ + public static final IndexerPermissionOption USER_IDS = fromString("userIds"); + + /** + * Indexer to ingest ACL groupIds from data source to index. + */ + public static final IndexerPermissionOption GROUP_IDS = fromString("groupIds"); + + /** + * Indexer to ingest Azure RBAC scope from data source to index. + */ + public static final IndexerPermissionOption RBAC_SCOPE = fromString("rbacScope"); + + /** + * Creates a new instance of IndexerPermissionOption value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public IndexerPermissionOption() { + } + + /** + * Creates or finds a IndexerPermissionOption from its string representation. + * + * @param name a name to look for. + * @return the corresponding IndexerPermissionOption. + */ + public static IndexerPermissionOption fromString(String name) { + return fromString(name, IndexerPermissionOption.class); + } + + /** + * Gets known IndexerPermissionOption values. + * + * @return known IndexerPermissionOption values. + */ + public static Collection values() { + return values(IndexerPermissionOption.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerResyncBody.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerResyncBody.java new file mode 100644 index 000000000000..2dffa250de57 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerResyncBody.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +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; + +/** + * The IndexerResyncBody model. + */ +@Fluent +public final class IndexerResyncBody implements JsonSerializable { + /* + * Re-sync options that have been pre-defined from data source. + */ + private List options; + + /** + * Creates an instance of IndexerResyncBody class. + */ + public IndexerResyncBody() { + } + + /** + * Get the options property: Re-sync options that have been pre-defined from data source. + * + * @return the options value. + */ + public List getOptions() { + return this.options; + } + + /** + * Set the options property: Re-sync options that have been pre-defined from data source. + * + * @param options the options value to set. + * @return the IndexerResyncBody object itself. + */ + public IndexerResyncBody setOptions(List options) { + this.options = options; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("options", this.options, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of IndexerResyncBody from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of IndexerResyncBody 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 IndexerResyncBody. + */ + public static IndexerResyncBody fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + IndexerResyncBody deserializedIndexerResyncBody = new IndexerResyncBody(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("options".equals(fieldName)) { + List options + = reader.readArray(reader1 -> IndexerResyncOption.fromString(reader1.getString())); + deserializedIndexerResyncBody.options = options; + } else { + reader.skipChildren(); + } + } + + return deserializedIndexerResyncBody; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerResyncOption.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerResyncOption.java new file mode 100644 index 000000000000..405744a5e443 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerResyncOption.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Options with various types of permission data to index. + */ +public final class IndexerResyncOption extends ExpandableStringEnum { + /** + * Indexer to re-ingest pre-selected permissions data from data source to index. + */ + public static final IndexerResyncOption PERMISSIONS = fromString("permissions"); + + /** + * Creates a new instance of IndexerResyncOption value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public IndexerResyncOption() { + } + + /** + * Creates or finds a IndexerResyncOption from its string representation. + * + * @param name a name to look for. + * @return the corresponding IndexerResyncOption. + */ + public static IndexerResyncOption fromString(String name) { + return fromString(name, IndexerResyncOption.class); + } + + /** + * Gets known IndexerResyncOption values. + * + * @return known IndexerResyncOption values. + */ + public static Collection values() { + return values(IndexerResyncOption.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingMode.java index 7d7b1e8f6fe8..e9b31355ebd7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexingMode.java @@ -24,6 +24,11 @@ public final class IndexingMode extends ExpandableStringEnum { */ public static final IndexingMode INDEXING_RESET_DOCS = fromString("indexingResetDocs"); + /** + * The indexer is resyncing and indexing selective option(s) from the datasource. + */ + public static final IndexingMode INDEXING_RESYNC = fromString("indexingResync"); + /** * Creates a new instance of IndexingMode value. * diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgent.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgent.java new file mode 100644 index 000000000000..56fb21c1048b --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgent.java @@ -0,0 +1,285 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +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.ArrayList; +import java.util.List; + +/** + * The KnowledgeAgent model. + */ +@Fluent +public final class KnowledgeAgent implements JsonSerializable { + /* + * The name of the knowledge agent. + */ + private final String name; + + /* + * Contains configuration options on how to connect to AI models. + */ + private final List models; + + /* + * The targetIndexes property. + */ + private final List targetIndexes; + + /* + * Guardrails to limit how much resources are utilized for a single agent retrieval request. + */ + private KnowledgeAgentRequestLimits requestLimits; + + /* + * The ETag of the agent. + */ + private String eTag; + + /* + * A description of an encryption key that you create in Azure Key Vault. This key is used to provide an additional + * level of encryption-at-rest for your agent definition when you want full assurance that no one, not even + * Microsoft, can decrypt them. Once you have encrypted your agent definition, it will always remain encrypted. The + * search service will ignore attempts to set this property to null. You can change this property as needed if you + * want to rotate your encryption key; Your agent definition will be unaffected. Encryption with customer-managed + * keys is not available for free search services, and is only available for paid services created on or after + * January 1, 2019. + */ + private SearchResourceEncryptionKey encryptionKey; + + /* + * The description of the agent. + */ + private String description; + + /** + * Creates an instance of KnowledgeAgent class. + * + * @param name the name value to set. + * @param models the models value to set. + * @param targetIndexes the targetIndexes value to set. + */ + public KnowledgeAgent(String name, List models, + List targetIndexes) { + this.name = name; + this.models = models; + this.targetIndexes = targetIndexes; + } + + /** + * Get the name property: The name of the knowledge agent. + * + * @return the name value. + */ + public String getName() { + return this.name; + } + + /** + * Get the models property: Contains configuration options on how to connect to AI models. + * + * @return the models value. + */ + public List getModels() { + return this.models; + } + + /** + * Get the targetIndexes property: The targetIndexes property. + * + * @return the targetIndexes value. + */ + public List getTargetIndexes() { + return this.targetIndexes; + } + + /** + * Get the requestLimits property: Guardrails to limit how much resources are utilized for a single agent retrieval + * request. + * + * @return the requestLimits value. + */ + public KnowledgeAgentRequestLimits getRequestLimits() { + return this.requestLimits; + } + + /** + * Set the requestLimits property: Guardrails to limit how much resources are utilized for a single agent retrieval + * request. + * + * @param requestLimits the requestLimits value to set. + * @return the KnowledgeAgent object itself. + */ + public KnowledgeAgent setRequestLimits(KnowledgeAgentRequestLimits requestLimits) { + this.requestLimits = requestLimits; + return this; + } + + /** + * Get the eTag property: The ETag of the agent. + * + * @return the eTag value. + */ + public String getETag() { + return this.eTag; + } + + /** + * Set the eTag property: The ETag of the agent. + * + * @param eTag the eTag value to set. + * @return the KnowledgeAgent object itself. + */ + public KnowledgeAgent setETag(String eTag) { + this.eTag = eTag; + return this; + } + + /** + * Get the encryptionKey property: A description of an encryption key that you create in Azure Key Vault. This key + * is used to provide an additional level of encryption-at-rest for your agent definition when you want full + * assurance that no one, not even Microsoft, can decrypt them. Once you have encrypted your agent definition, it + * will always remain encrypted. The search service will ignore attempts to set this property to null. You can + * change this property as needed if you want to rotate your encryption key; Your agent definition will be + * unaffected. Encryption with customer-managed keys is not available for free search services, and is only + * available for paid services created on or after January 1, 2019. + * + * @return the encryptionKey value. + */ + public SearchResourceEncryptionKey getEncryptionKey() { + return this.encryptionKey; + } + + /** + * Set the encryptionKey property: A description of an encryption key that you create in Azure Key Vault. This key + * is used to provide an additional level of encryption-at-rest for your agent definition when you want full + * assurance that no one, not even Microsoft, can decrypt them. Once you have encrypted your agent definition, it + * will always remain encrypted. The search service will ignore attempts to set this property to null. You can + * change this property as needed if you want to rotate your encryption key; Your agent definition will be + * unaffected. Encryption with customer-managed keys is not available for free search services, and is only + * available for paid services created on or after January 1, 2019. + * + * @param encryptionKey the encryptionKey value to set. + * @return the KnowledgeAgent object itself. + */ + public KnowledgeAgent setEncryptionKey(SearchResourceEncryptionKey encryptionKey) { + this.encryptionKey = encryptionKey; + return this; + } + + /** + * Get the description property: The description of the agent. + * + * @return the description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Set the description property: The description of the agent. + * + * @param description the description value to set. + * @return the KnowledgeAgent object itself. + */ + public KnowledgeAgent setDescription(String description) { + this.description = description; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", this.name); + jsonWriter.writeArrayField("models", this.models, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeArrayField("targetIndexes", this.targetIndexes, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeJsonField("requestLimits", this.requestLimits); + jsonWriter.writeStringField("@odata.etag", this.eTag); + jsonWriter.writeJsonField("encryptionKey", this.encryptionKey); + jsonWriter.writeStringField("description", this.description); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgent from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgent 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 KnowledgeAgent. + */ + public static KnowledgeAgent fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean nameFound = false; + String name = null; + boolean modelsFound = false; + List models = null; + boolean targetIndexesFound = false; + List targetIndexes = null; + KnowledgeAgentRequestLimits requestLimits = null; + String eTag = null; + SearchResourceEncryptionKey encryptionKey = null; + String description = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("name".equals(fieldName)) { + name = reader.getString(); + nameFound = true; + } else if ("models".equals(fieldName)) { + models = reader.readArray(reader1 -> KnowledgeAgentModel.fromJson(reader1)); + modelsFound = true; + } else if ("targetIndexes".equals(fieldName)) { + targetIndexes = reader.readArray(reader1 -> KnowledgeAgentTargetIndex.fromJson(reader1)); + targetIndexesFound = true; + } else if ("requestLimits".equals(fieldName)) { + requestLimits = KnowledgeAgentRequestLimits.fromJson(reader); + } else if ("@odata.etag".equals(fieldName)) { + eTag = reader.getString(); + } else if ("encryptionKey".equals(fieldName)) { + encryptionKey = SearchResourceEncryptionKey.fromJson(reader); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else { + reader.skipChildren(); + } + } + if (nameFound && modelsFound && targetIndexesFound) { + KnowledgeAgent deserializedKnowledgeAgent = new KnowledgeAgent(name, models, targetIndexes); + deserializedKnowledgeAgent.requestLimits = requestLimits; + deserializedKnowledgeAgent.eTag = eTag; + deserializedKnowledgeAgent.encryptionKey = encryptionKey; + deserializedKnowledgeAgent.description = description; + + return deserializedKnowledgeAgent; + } + List missingProperties = new ArrayList<>(); + if (!nameFound) { + missingProperties.add("name"); + } + if (!modelsFound) { + missingProperties.add("models"); + } + if (!targetIndexesFound) { + missingProperties.add("targetIndexes"); + } + + throw new IllegalStateException( + "Missing required property/properties: " + String.join(", ", missingProperties)); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentAzureOpenAIModel.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentAzureOpenAIModel.java new file mode 100644 index 000000000000..e4bc03c9a7ec --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentAzureOpenAIModel.java @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +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; + +/** + * Specifies the Azure OpenAI resource used to do query planning. + */ +@Immutable +public final class KnowledgeAgentAzureOpenAIModel extends KnowledgeAgentModel { + /* + * The type of AI model. + */ + private KnowledgeAgentModelKind kind = KnowledgeAgentModelKind.AZURE_OPEN_AI; + + /* + * Contains the parameters specific to Azure OpenAI model endpoint. + */ + private final AzureOpenAIVectorizerParameters azureOpenAIParameters; + + /** + * Creates an instance of KnowledgeAgentAzureOpenAIModel class. + * + * @param azureOpenAIParameters the azureOpenAIParameters value to set. + */ + public KnowledgeAgentAzureOpenAIModel(AzureOpenAIVectorizerParameters azureOpenAIParameters) { + this.azureOpenAIParameters = azureOpenAIParameters; + } + + /** + * Get the kind property: The type of AI model. + * + * @return the kind value. + */ + @Override + public KnowledgeAgentModelKind getKind() { + return this.kind; + } + + /** + * Get the azureOpenAIParameters property: Contains the parameters specific to Azure OpenAI model endpoint. + * + * @return the azureOpenAIParameters value. + */ + public AzureOpenAIVectorizerParameters getAzureOpenAIParameters() { + return this.azureOpenAIParameters; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeJsonField("azureOpenAIParameters", this.azureOpenAIParameters); + jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentAzureOpenAIModel from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentAzureOpenAIModel 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 KnowledgeAgentAzureOpenAIModel. + */ + public static KnowledgeAgentAzureOpenAIModel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean azureOpenAIParametersFound = false; + AzureOpenAIVectorizerParameters azureOpenAIParameters = null; + KnowledgeAgentModelKind kind = KnowledgeAgentModelKind.AZURE_OPEN_AI; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("azureOpenAIParameters".equals(fieldName)) { + azureOpenAIParameters = AzureOpenAIVectorizerParameters.fromJson(reader); + azureOpenAIParametersFound = true; + } else if ("kind".equals(fieldName)) { + kind = KnowledgeAgentModelKind.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + if (azureOpenAIParametersFound) { + KnowledgeAgentAzureOpenAIModel deserializedKnowledgeAgentAzureOpenAIModel + = new KnowledgeAgentAzureOpenAIModel(azureOpenAIParameters); + deserializedKnowledgeAgentAzureOpenAIModel.kind = kind; + + return deserializedKnowledgeAgentAzureOpenAIModel; + } + throw new IllegalStateException("Missing required property: azureOpenAIParameters"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentModel.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentModel.java new file mode 100644 index 000000000000..c90531ec7960 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentModel.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +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; + +/** + * Specifies the connection parameters for the model to use for query planning. + */ +@Immutable +public class KnowledgeAgentModel implements JsonSerializable { + /* + * The type of AI model. + */ + private KnowledgeAgentModelKind kind = KnowledgeAgentModelKind.fromString("KnowledgeAgentModel"); + + /** + * Creates an instance of KnowledgeAgentModel class. + */ + public KnowledgeAgentModel() { + } + + /** + * Get the kind property: The type of AI model. + * + * @return the kind value. + */ + public KnowledgeAgentModelKind getKind() { + return this.kind; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentModel from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentModel 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 KnowledgeAgentModel. + */ + public static KnowledgeAgentModel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + readerToUse.nextToken(); // Prepare for reading + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("kind".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("azureOpenAI".equals(discriminatorValue)) { + return KnowledgeAgentAzureOpenAIModel.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + static KnowledgeAgentModel fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + KnowledgeAgentModel deserializedKnowledgeAgentModel = new KnowledgeAgentModel(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("kind".equals(fieldName)) { + deserializedKnowledgeAgentModel.kind = KnowledgeAgentModelKind.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedKnowledgeAgentModel; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentModelKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentModelKind.java new file mode 100644 index 000000000000..3f4f1dbc523a --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentModelKind.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The AI model to be used for query planning. + */ +public final class KnowledgeAgentModelKind extends ExpandableStringEnum { + /** + * Use Azure Open AI models for query planning. + */ + public static final KnowledgeAgentModelKind AZURE_OPEN_AI = fromString("azureOpenAI"); + + /** + * Creates a new instance of KnowledgeAgentModelKind value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public KnowledgeAgentModelKind() { + } + + /** + * Creates or finds a KnowledgeAgentModelKind from its string representation. + * + * @param name a name to look for. + * @return the corresponding KnowledgeAgentModelKind. + */ + public static KnowledgeAgentModelKind fromString(String name) { + return fromString(name, KnowledgeAgentModelKind.class); + } + + /** + * Gets known KnowledgeAgentModelKind values. + * + * @return known KnowledgeAgentModelKind values. + */ + public static Collection values() { + return values(KnowledgeAgentModelKind.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentRequestLimits.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentRequestLimits.java new file mode 100644 index 000000000000..f24368e8b218 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentRequestLimits.java @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Guardrails to limit how much resources are utilized for a single agent retrieval request. + */ +@Fluent +public final class KnowledgeAgentRequestLimits implements JsonSerializable { + /* + * The maximum runtime in seconds. + */ + private Integer maxRuntimeInSeconds; + + /* + * Limits the maximum size of the content in the output. + */ + private Integer maxOutputSize; + + /** + * Creates an instance of KnowledgeAgentRequestLimits class. + */ + public KnowledgeAgentRequestLimits() { + } + + /** + * Get the maxRuntimeInSeconds property: The maximum runtime in seconds. + * + * @return the maxRuntimeInSeconds value. + */ + public Integer getMaxRuntimeInSeconds() { + return this.maxRuntimeInSeconds; + } + + /** + * Set the maxRuntimeInSeconds property: The maximum runtime in seconds. + * + * @param maxRuntimeInSeconds the maxRuntimeInSeconds value to set. + * @return the KnowledgeAgentRequestLimits object itself. + */ + public KnowledgeAgentRequestLimits setMaxRuntimeInSeconds(Integer maxRuntimeInSeconds) { + this.maxRuntimeInSeconds = maxRuntimeInSeconds; + return this; + } + + /** + * Get the maxOutputSize property: Limits the maximum size of the content in the output. + * + * @return the maxOutputSize value. + */ + public Integer getMaxOutputSize() { + return this.maxOutputSize; + } + + /** + * Set the maxOutputSize property: Limits the maximum size of the content in the output. + * + * @param maxOutputSize the maxOutputSize value to set. + * @return the KnowledgeAgentRequestLimits object itself. + */ + public KnowledgeAgentRequestLimits setMaxOutputSize(Integer maxOutputSize) { + this.maxOutputSize = maxOutputSize; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeNumberField("maxRuntimeInSeconds", this.maxRuntimeInSeconds); + jsonWriter.writeNumberField("maxOutputSize", this.maxOutputSize); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentRequestLimits from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentRequestLimits 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 KnowledgeAgentRequestLimits. + */ + public static KnowledgeAgentRequestLimits fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + KnowledgeAgentRequestLimits deserializedKnowledgeAgentRequestLimits = new KnowledgeAgentRequestLimits(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("maxRuntimeInSeconds".equals(fieldName)) { + deserializedKnowledgeAgentRequestLimits.maxRuntimeInSeconds + = reader.getNullable(JsonReader::getInt); + } else if ("maxOutputSize".equals(fieldName)) { + deserializedKnowledgeAgentRequestLimits.maxOutputSize = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + + return deserializedKnowledgeAgentRequestLimits; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentTargetIndex.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentTargetIndex.java new file mode 100644 index 000000000000..0442b3a36827 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeAgentTargetIndex.java @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.annotation.Fluent; +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 KnowledgeAgentTargetIndex model. + */ +@Fluent +public final class KnowledgeAgentTargetIndex implements JsonSerializable { + /* + * The name of the target index. + */ + private final String indexName; + + /* + * A threshold for reranking results (range: 0-4). + */ + private Float defaultRerankerThreshold; + + /* + * Indicates whether reference source data should be included. + */ + private Boolean defaultIncludeReferenceSourceData; + + /* + * Limits the number of documents considered for ranking. + */ + private Integer defaultMaxDocsForReranker; + + /** + * Creates an instance of KnowledgeAgentTargetIndex class. + * + * @param indexName the indexName value to set. + */ + public KnowledgeAgentTargetIndex(String indexName) { + this.indexName = indexName; + } + + /** + * Get the indexName property: The name of the target index. + * + * @return the indexName value. + */ + public String getIndexName() { + return this.indexName; + } + + /** + * Get the defaultRerankerThreshold property: A threshold for reranking results (range: 0-4). + * + * @return the defaultRerankerThreshold value. + */ + public Float getDefaultRerankerThreshold() { + return this.defaultRerankerThreshold; + } + + /** + * Set the defaultRerankerThreshold property: A threshold for reranking results (range: 0-4). + * + * @param defaultRerankerThreshold the defaultRerankerThreshold value to set. + * @return the KnowledgeAgentTargetIndex object itself. + */ + public KnowledgeAgentTargetIndex setDefaultRerankerThreshold(Float defaultRerankerThreshold) { + this.defaultRerankerThreshold = defaultRerankerThreshold; + return this; + } + + /** + * Get the defaultIncludeReferenceSourceData property: Indicates whether reference source data should be included. + * + * @return the defaultIncludeReferenceSourceData value. + */ + public Boolean isDefaultIncludeReferenceSourceData() { + return this.defaultIncludeReferenceSourceData; + } + + /** + * Set the defaultIncludeReferenceSourceData property: Indicates whether reference source data should be included. + * + * @param defaultIncludeReferenceSourceData the defaultIncludeReferenceSourceData value to set. + * @return the KnowledgeAgentTargetIndex object itself. + */ + public KnowledgeAgentTargetIndex setDefaultIncludeReferenceSourceData(Boolean defaultIncludeReferenceSourceData) { + this.defaultIncludeReferenceSourceData = defaultIncludeReferenceSourceData; + return this; + } + + /** + * Get the defaultMaxDocsForReranker property: Limits the number of documents considered for ranking. + * + * @return the defaultMaxDocsForReranker value. + */ + public Integer getDefaultMaxDocsForReranker() { + return this.defaultMaxDocsForReranker; + } + + /** + * Set the defaultMaxDocsForReranker property: Limits the number of documents considered for ranking. + * + * @param defaultMaxDocsForReranker the defaultMaxDocsForReranker value to set. + * @return the KnowledgeAgentTargetIndex object itself. + */ + public KnowledgeAgentTargetIndex setDefaultMaxDocsForReranker(Integer defaultMaxDocsForReranker) { + this.defaultMaxDocsForReranker = defaultMaxDocsForReranker; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("indexName", this.indexName); + jsonWriter.writeNumberField("defaultRerankerThreshold", this.defaultRerankerThreshold); + jsonWriter.writeBooleanField("defaultIncludeReferenceSourceData", this.defaultIncludeReferenceSourceData); + jsonWriter.writeNumberField("defaultMaxDocsForReranker", this.defaultMaxDocsForReranker); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KnowledgeAgentTargetIndex from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KnowledgeAgentTargetIndex 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 KnowledgeAgentTargetIndex. + */ + public static KnowledgeAgentTargetIndex fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean indexNameFound = false; + String indexName = null; + Float defaultRerankerThreshold = null; + Boolean defaultIncludeReferenceSourceData = null; + Integer defaultMaxDocsForReranker = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("indexName".equals(fieldName)) { + indexName = reader.getString(); + indexNameFound = true; + } else if ("defaultRerankerThreshold".equals(fieldName)) { + defaultRerankerThreshold = reader.getNullable(JsonReader::getFloat); + } else if ("defaultIncludeReferenceSourceData".equals(fieldName)) { + defaultIncludeReferenceSourceData = reader.getNullable(JsonReader::getBoolean); + } else if ("defaultMaxDocsForReranker".equals(fieldName)) { + defaultMaxDocsForReranker = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + if (indexNameFound) { + KnowledgeAgentTargetIndex deserializedKnowledgeAgentTargetIndex + = new KnowledgeAgentTargetIndex(indexName); + deserializedKnowledgeAgentTargetIndex.defaultRerankerThreshold = defaultRerankerThreshold; + deserializedKnowledgeAgentTargetIndex.defaultIncludeReferenceSourceData + = defaultIncludeReferenceSourceData; + deserializedKnowledgeAgentTargetIndex.defaultMaxDocsForReranker = defaultMaxDocsForReranker; + + return deserializedKnowledgeAgentTargetIndex; + } + throw new IllegalStateException("Missing required property: indexName"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ListKnowledgeAgentsResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ListKnowledgeAgentsResult.java new file mode 100644 index 000000000000..5995635d7c9e --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ListKnowledgeAgentsResult.java @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +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; + +/** + * The ListKnowledgeAgentsResult model. + */ +@Immutable +public final class ListKnowledgeAgentsResult implements JsonSerializable { + /* + * The value property. + */ + private final List knowledgeAgents; + + /** + * Creates an instance of ListKnowledgeAgentsResult class. + * + * @param knowledgeAgents the knowledgeAgents value to set. + */ + public ListKnowledgeAgentsResult(List knowledgeAgents) { + this.knowledgeAgents = knowledgeAgents; + } + + /** + * Get the knowledgeAgents property: The value property. + * + * @return the knowledgeAgents value. + */ + public List getKnowledgeAgents() { + return this.knowledgeAgents; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeArrayField("value", this.knowledgeAgents, (writer, element) -> writer.writeJson(element)); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of ListKnowledgeAgentsResult from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of ListKnowledgeAgentsResult 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 ListKnowledgeAgentsResult. + */ + public static ListKnowledgeAgentsResult fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + boolean knowledgeAgentsFound = false; + List knowledgeAgents = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("value".equals(fieldName)) { + knowledgeAgents = reader.readArray(reader1 -> KnowledgeAgent.fromJson(reader1)); + knowledgeAgentsFound = true; + } else { + reader.skipChildren(); + } + } + if (knowledgeAgentsFound) { + return new ListKnowledgeAgentsResult(knowledgeAgents); + } + throw new IllegalStateException("Missing required property: value"); + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PermissionFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PermissionFilter.java new file mode 100644 index 000000000000..bf1c8d0d322c --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PermissionFilter.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * A value indicating whether the field should be used as a permission filter. + */ +public final class PermissionFilter extends ExpandableStringEnum { + /** + * Field represents user IDs that should be used to filter document access on queries. + */ + public static final PermissionFilter USER_IDS = fromString("userIds"); + + /** + * Field represents group IDs that should be used to filter document access on queries. + */ + public static final PermissionFilter GROUP_IDS = fromString("groupIds"); + + /** + * Field represents an RBAC scope that should be used to filter document access on queries. + */ + public static final PermissionFilter RBAC_SCOPE = fromString("rbacScope"); + + /** + * Creates a new instance of PermissionFilter value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public PermissionFilter() { + } + + /** + * Creates or finds a PermissionFilter from its string representation. + * + * @param name a name to look for. + * @return the corresponding PermissionFilter. + */ + public static PermissionFilter fromString(String name) { + return fromString(name, PermissionFilter.class); + } + + /** + * Gets known PermissionFilter values. + * + * @return known PermissionFilter values. + */ + public static Collection values() { + return values(PermissionFilter.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RankingOrder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RankingOrder.java new file mode 100644 index 000000000000..a07609c981ff --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RankingOrder.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * Represents score to use for sort order of documents. + */ +public final class RankingOrder extends ExpandableStringEnum { + /** + * Sets sort order as BoostedRerankerScore. + */ + public static final RankingOrder BOOSTED_RERANKER_SCORE = fromString("BoostedRerankerScore"); + + /** + * Sets sort order as ReRankerScore. + */ + public static final RankingOrder RE_RANKER_SCORE = fromString("RerankerScore"); + + /** + * Creates a new instance of RankingOrder value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public RankingOrder() { + } + + /** + * Creates or finds a RankingOrder from its string representation. + * + * @param name a name to look for. + * @return the corresponding RankingOrder. + */ + public static RankingOrder fromString(String name) { + return fromString(name, RankingOrder.class); + } + + /** + * Gets known RankingOrder values. + * + * @return known RankingOrder values. + */ + public static Collection values() { + return values(RankingOrder.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchField.java index ca321e5c6fb8..779a663582e3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchField.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchField.java @@ -100,6 +100,11 @@ public final class SearchField implements JsonSerializable { */ private Boolean facetable; + /* + * A value indicating whether the field should be used as a permission filter. + */ + private PermissionFilter permissionFilter; + /* * The name of the analyzer to use for the field. This option can be used only with searchable fields and it can't * be set together with either searchAnalyzer or indexAnalyzer. Once the analyzer is chosen, it cannot be changed @@ -401,6 +406,26 @@ public SearchField setFacetable(Boolean facetable) { return this; } + /** + * Get the permissionFilter property: A value indicating whether the field should be used as a permission filter. + * + * @return the permissionFilter value. + */ + public PermissionFilter getPermissionFilter() { + return this.permissionFilter; + } + + /** + * Set the permissionFilter property: A value indicating whether the field should be used as a permission filter. + * + * @param permissionFilter the permissionFilter value to set. + * @return the SearchField object itself. + */ + public SearchField setPermissionFilter(PermissionFilter permissionFilter) { + this.permissionFilter = permissionFilter; + return this; + } + /** * Get the analyzerName property: The name of the analyzer to use for the field. This option can be used only with * searchable fields and it can't be set together with either searchAnalyzer or indexAnalyzer. Once the analyzer is @@ -632,6 +657,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeBooleanField("filterable", this.filterable); jsonWriter.writeBooleanField("sortable", this.sortable); jsonWriter.writeBooleanField("facetable", this.facetable); + jsonWriter.writeStringField("permissionFilter", + this.permissionFilter == null ? null : this.permissionFilter.toString()); jsonWriter.writeStringField("analyzer", this.analyzerName == null ? null : this.analyzerName.toString()); jsonWriter.writeStringField("searchAnalyzer", this.searchAnalyzerName == null ? null : this.searchAnalyzerName.toString()); @@ -670,6 +697,7 @@ public static SearchField fromJson(JsonReader jsonReader) throws IOException { Boolean filterable = null; Boolean sortable = null; Boolean facetable = null; + PermissionFilter permissionFilter = null; LexicalAnalyzerName analyzerName = null; LexicalAnalyzerName searchAnalyzerName = null; LexicalAnalyzerName indexAnalyzerName = null; @@ -702,6 +730,8 @@ public static SearchField fromJson(JsonReader jsonReader) throws IOException { sortable = reader.getNullable(JsonReader::getBoolean); } else if ("facetable".equals(fieldName)) { facetable = reader.getNullable(JsonReader::getBoolean); + } else if ("permissionFilter".equals(fieldName)) { + permissionFilter = PermissionFilter.fromString(reader.getString()); } else if ("analyzer".equals(fieldName)) { analyzerName = LexicalAnalyzerName.fromString(reader.getString()); } else if ("searchAnalyzer".equals(fieldName)) { @@ -733,6 +763,7 @@ public static SearchField fromJson(JsonReader jsonReader) throws IOException { deserializedSearchField.filterable = filterable; deserializedSearchField.sortable = sortable; deserializedSearchField.facetable = facetable; + deserializedSearchField.permissionFilter = permissionFilter; deserializedSearchField.analyzerName = analyzerName; deserializedSearchField.searchAnalyzerName = searchAnalyzerName; deserializedSearchField.indexAnalyzerName = indexAnalyzerName; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndex.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndex.java index c28a6e4029f5..9f9e18b35083 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndex.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndex.java @@ -25,6 +25,11 @@ public final class SearchIndex implements JsonSerializable { */ private final String name; + /* + * The description of the index. + */ + private String description; + /* * The fields of the index. */ @@ -103,6 +108,11 @@ public final class SearchIndex implements JsonSerializable { */ private VectorSearch vectorSearch; + /* + * A value indicating whether permission filtering is enabled for the index. + */ + private SearchIndexPermissionFilterOption permissionFilterOption; + /* * The ETag of the index. */ @@ -126,6 +136,26 @@ public String getName() { return this.name; } + /** + * Get the description property: The description of the index. + * + * @return the description value. + */ + public String getDescription() { + return this.description; + } + + /** + * Set the description property: The description of the index. + * + * @param description the description value to set. + * @return the SearchIndex object itself. + */ + public SearchIndex setDescription(String description) { + this.description = description; + return this; + } + /** * Get the fields property: The fields of the index. * @@ -426,6 +456,28 @@ public SearchIndex setVectorSearch(VectorSearch vectorSearch) { return this; } + /** + * Get the permissionFilterOption property: A value indicating whether permission filtering is enabled for the + * index. + * + * @return the permissionFilterOption value. + */ + public SearchIndexPermissionFilterOption getPermissionFilterOption() { + return this.permissionFilterOption; + } + + /** + * Set the permissionFilterOption property: A value indicating whether permission filtering is enabled for the + * index. + * + * @param permissionFilterOption the permissionFilterOption value to set. + * @return the SearchIndex object itself. + */ + public SearchIndex setPermissionFilterOption(SearchIndexPermissionFilterOption permissionFilterOption) { + this.permissionFilterOption = permissionFilterOption; + return this; + } + /** * Get the eTag property: The ETag of the index. * @@ -453,6 +505,7 @@ public SearchIndex setETag(String eTag) { public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", this.name); + jsonWriter.writeStringField("description", this.description); jsonWriter.writeArrayField("fields", this.fields, (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("scoringProfiles", this.scoringProfiles, (writer, element) -> writer.writeJson(element)); @@ -468,6 +521,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeJsonField("similarity", this.similarity); jsonWriter.writeJsonField("semantic", this.semanticSearch); jsonWriter.writeJsonField("vectorSearch", this.vectorSearch); + jsonWriter.writeStringField("permissionFilterOption", + this.permissionFilterOption == null ? null : this.permissionFilterOption.toString()); jsonWriter.writeStringField("@odata.etag", this.eTag); return jsonWriter.writeEndObject(); } @@ -485,6 +540,7 @@ public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { boolean nameFound = false; String name = null; + String description = null; List fields = null; List scoringProfiles = null; String defaultScoringProfile = null; @@ -499,6 +555,7 @@ public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { SimilarityAlgorithm similarity = null; SemanticSearch semanticSearch = null; VectorSearch vectorSearch = null; + SearchIndexPermissionFilterOption permissionFilterOption = null; String eTag = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); @@ -506,6 +563,8 @@ public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { if ("name".equals(fieldName)) { name = reader.getString(); nameFound = true; + } else if ("description".equals(fieldName)) { + description = reader.getString(); } else if ("fields".equals(fieldName)) { fields = reader.readArray(reader1 -> SearchField.fromJson(reader1)); } else if ("scoringProfiles".equals(fieldName)) { @@ -534,6 +593,8 @@ public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { semanticSearch = SemanticSearch.fromJson(reader); } else if ("vectorSearch".equals(fieldName)) { vectorSearch = VectorSearch.fromJson(reader); + } else if ("permissionFilterOption".equals(fieldName)) { + permissionFilterOption = SearchIndexPermissionFilterOption.fromString(reader.getString()); } else if ("@odata.etag".equals(fieldName)) { eTag = reader.getString(); } else { @@ -542,6 +603,7 @@ public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { } if (nameFound) { SearchIndex deserializedSearchIndex = new SearchIndex(name); + deserializedSearchIndex.description = description; deserializedSearchIndex.fields = fields; deserializedSearchIndex.scoringProfiles = scoringProfiles; deserializedSearchIndex.defaultScoringProfile = defaultScoringProfile; @@ -556,6 +618,7 @@ public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { deserializedSearchIndex.similarity = similarity; deserializedSearchIndex.semanticSearch = semanticSearch; deserializedSearchIndex.vectorSearch = vectorSearch; + deserializedSearchIndex.permissionFilterOption = permissionFilterOption; deserializedSearchIndex.eTag = eTag; return deserializedSearchIndex; } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexPermissionFilterOption.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexPermissionFilterOption.java new file mode 100644 index 000000000000..b9577c33fc39 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexPermissionFilterOption.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.indexes.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * A value indicating whether permission filtering is enabled for the index. + */ +public final class SearchIndexPermissionFilterOption extends ExpandableStringEnum { + /** + * Static value enabled for SearchIndexPermissionFilterOption. + */ + public static final SearchIndexPermissionFilterOption ENABLED = fromString("enabled"); + + /** + * Static value disabled for SearchIndexPermissionFilterOption. + */ + public static final SearchIndexPermissionFilterOption DISABLED = fromString("disabled"); + + /** + * Creates a new instance of SearchIndexPermissionFilterOption value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public SearchIndexPermissionFilterOption() { + } + + /** + * Creates or finds a SearchIndexPermissionFilterOption from its string representation. + * + * @param name a name to look for. + * @return the corresponding SearchIndexPermissionFilterOption. + */ + public static SearchIndexPermissionFilterOption fromString(String name) { + return fromString(name, SearchIndexPermissionFilterOption.class); + } + + /** + * Gets known SearchIndexPermissionFilterOption values. + * + * @return known SearchIndexPermissionFilterOption values. + */ + public static Collection values() { + return values(SearchIndexPermissionFilterOption.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceConnection.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceConnection.java index 24e63cb2cc49..5ef5814bedea 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceConnection.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceConnection.java @@ -12,6 +12,7 @@ import com.azure.json.JsonWriter; import com.azure.search.documents.indexes.implementation.models.DataSourceCredentials; import java.io.IOException; +import java.util.List; /** * Represents a datasource definition, which can be used to configure an indexer. @@ -51,6 +52,11 @@ public final class SearchIndexerDataSourceConnection implements JsonSerializable */ private SearchIndexerDataIdentity identity; + /* + * Ingestion options with various types of permission data. + */ + private List indexerPermissionOptions; + /* * The data change detection policy for the datasource. */ @@ -179,6 +185,27 @@ public SearchIndexerDataSourceConnection setIdentity(SearchIndexerDataIdentity i return this; } + /** + * Get the indexerPermissionOptions property: Ingestion options with various types of permission data. + * + * @return the indexerPermissionOptions value. + */ + public List getIndexerPermissionOptions() { + return this.indexerPermissionOptions; + } + + /** + * Set the indexerPermissionOptions property: Ingestion options with various types of permission data. + * + * @param indexerPermissionOptions the indexerPermissionOptions value to set. + * @return the SearchIndexerDataSourceConnection object itself. + */ + public SearchIndexerDataSourceConnection + setIndexerPermissionOptions(List indexerPermissionOptions) { + this.indexerPermissionOptions = indexerPermissionOptions; + return this; + } + /** * Get the dataChangeDetectionPolicy property: The data change detection policy for the datasource. * @@ -285,6 +312,8 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeJsonField("credentials", this.credentials); jsonWriter.writeJsonField("container", this.container); jsonWriter.writeJsonField("identity", this.identity); + jsonWriter.writeArrayField("indexerPermissionOptions", this.indexerPermissionOptions, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); jsonWriter.writeJsonField("dataChangeDetectionPolicy", this.dataChangeDetectionPolicy); jsonWriter.writeJsonField("dataDeletionDetectionPolicy", this.dataDeletionDetectionPolicy); jsonWriter.writeStringField("@odata.etag", this.eTag); @@ -310,6 +339,7 @@ public static SearchIndexerDataSourceConnection fromJson(JsonReader jsonReader) DataSourceCredentials credentials = null; SearchIndexerDataContainer container = null; SearchIndexerDataIdentity identity = null; + List indexerPermissionOptions = null; DataChangeDetectionPolicy dataChangeDetectionPolicy = null; DataDeletionDetectionPolicy dataDeletionDetectionPolicy = null; String eTag = null; @@ -330,6 +360,9 @@ public static SearchIndexerDataSourceConnection fromJson(JsonReader jsonReader) container = SearchIndexerDataContainer.fromJson(reader); } else if ("identity".equals(fieldName)) { identity = SearchIndexerDataIdentity.fromJson(reader); + } else if ("indexerPermissionOptions".equals(fieldName)) { + indexerPermissionOptions + = reader.readArray(reader1 -> IndexerPermissionOption.fromString(reader1.getString())); } else if ("dataChangeDetectionPolicy".equals(fieldName)) { dataChangeDetectionPolicy = DataChangeDetectionPolicy.fromJson(reader); } else if ("dataDeletionDetectionPolicy".equals(fieldName)) { @@ -350,6 +383,7 @@ public static SearchIndexerDataSourceConnection fromJson(JsonReader jsonReader) deserializedSearchIndexerDataSourceConnection.credentials = credentials; deserializedSearchIndexerDataSourceConnection.container = container; deserializedSearchIndexerDataSourceConnection.identity = identity; + deserializedSearchIndexerDataSourceConnection.indexerPermissionOptions = indexerPermissionOptions; deserializedSearchIndexerDataSourceConnection.dataChangeDetectionPolicy = dataChangeDetectionPolicy; deserializedSearchIndexerDataSourceConnection.dataDeletionDetectionPolicy = dataDeletionDetectionPolicy; deserializedSearchIndexerDataSourceConnection.eTag = eTag; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkill.java index bf65c2fe7c7b..71f21485e07d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkill.java @@ -236,7 +236,9 @@ public static SearchIndexerSkill fromJson(JsonReader jsonReader) throws IOExcept } else if ("#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill".equals(discriminatorValue)) { return DocumentIntelligenceLayoutSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Custom.WebApiSkill".equals(discriminatorValue)) { - return WebApiSkill.fromJson(readerToUse.reset()); + return WebApiSkill.fromJsonKnownDiscriminator(readerToUse.reset()); + } else if ("#Microsoft.Skills.Custom.ChatCompletionSkill".equals(discriminatorValue)) { + return ChatCompletionSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Custom.AmlSkill".equals(discriminatorValue)) { return AzureMachineLearningSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill".equals(discriminatorValue)) { diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerStatus.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerStatus.java index 70d70fb08e08..8cff4450a13d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerStatus.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexerStatus.java @@ -40,6 +40,11 @@ public final class SearchIndexerStatus implements JsonSerializable { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + readerToUse.nextToken(); // Prepare for reading + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("@odata.type".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("#Microsoft.Skills.Custom.ChatCompletionSkill".equals(discriminatorValue)) { + return ChatCompletionSkill.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + static WebApiSkill fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { boolean inputsFound = false; List inputs = null; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentDebugInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentDebugInfo.java index c73f1333369f..49b1ff33f1e3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentDebugInfo.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DocumentDebugInfo.java @@ -12,6 +12,8 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.List; +import java.util.Map; /** * Contains debugging information that can be used to further explore your search results. @@ -28,6 +30,11 @@ public final class DocumentDebugInfo implements JsonSerializable> innerHits; + /** * Creates an instance of DocumentDebugInfo class. */ @@ -52,6 +59,16 @@ public VectorsDebugInfo getVectors() { return this.vectors; } + /** + * Get the innerHits property: Contains debugging information specific to vectors matched within a collection of + * complex types. + * + * @return the innerHits value. + */ + public Map> getInnerHits() { + return this.innerHits; + } + /** * {@inheritDoc} */ @@ -80,6 +97,10 @@ public static DocumentDebugInfo fromJson(JsonReader jsonReader) throws IOExcepti deserializedDocumentDebugInfo.semantic = SemanticDebugInfo.fromJson(reader); } else if ("vectors".equals(fieldName)) { deserializedDocumentDebugInfo.vectors = VectorsDebugInfo.fromJson(reader); + } else if ("innerHits".equals(fieldName)) { + Map> innerHits = reader.readMap( + reader1 -> reader1.readArray(reader2 -> QueryResultDocumentInnerHit.fromJson(reader2))); + deserializedDocumentDebugInfo.innerHits = innerHits; } else { reader.skipChildren(); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryDebugMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryDebugMode.java index 6ae5ade78bfb..40844177f452 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryDebugMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryDebugMode.java @@ -34,6 +34,11 @@ public final class QueryDebugMode extends ExpandableStringEnum { */ public static final QueryDebugMode QUERY_REWRITES = fromString("queryRewrites"); + /** + * Allows the user to retrieve scoring information regarding vectors matched within a collection of complex types. + */ + public static final QueryDebugMode INNER_HITS = fromString("innerHits"); + /** * Turn on all debug options. */ diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentInnerHit.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentInnerHit.java new file mode 100644 index 000000000000..11198caaa8ae --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentInnerHit.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package com.azure.search.documents.models; + +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; +import java.util.Map; + +/** + * Detailed scoring information for an individual element of a complex collection. + */ +@Immutable +public final class QueryResultDocumentInnerHit implements JsonSerializable { + /* + * Position of this specific matching element within it's original collection. Position starts at 0. + */ + private Long ordinal; + + /* + * Detailed scoring information for an individual element of a complex collection that matched a vector query. + */ + private List> vectors; + + /** + * Creates an instance of QueryResultDocumentInnerHit class. + */ + public QueryResultDocumentInnerHit() { + } + + /** + * Get the ordinal property: Position of this specific matching element within it's original collection. Position + * starts at 0. + * + * @return the ordinal value. + */ + public Long getOrdinal() { + return this.ordinal; + } + + /** + * Get the vectors property: Detailed scoring information for an individual element of a complex collection that + * matched a vector query. + * + * @return the vectors value. + */ + public List> getVectors() { + return this.vectors; + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of QueryResultDocumentInnerHit from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of QueryResultDocumentInnerHit 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 QueryResultDocumentInnerHit. + */ + public static QueryResultDocumentInnerHit fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + QueryResultDocumentInnerHit deserializedQueryResultDocumentInnerHit = new QueryResultDocumentInnerHit(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("ordinal".equals(fieldName)) { + deserializedQueryResultDocumentInnerHit.ordinal = reader.getNullable(JsonReader::getLong); + } else if ("vectors".equals(fieldName)) { + List> vectors = reader + .readArray(reader1 -> reader1.readMap(reader2 -> SingleVectorFieldResult.fromJson(reader2))); + deserializedQueryResultDocumentInnerHit.vectors = vectors; + } else { + reader.skipChildren(); + } + } + + return deserializedQueryResultDocumentInnerHit; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResult.java index 61dd60953475..f3659c82caed 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchResult.java @@ -71,8 +71,8 @@ public void setJsonSerializer(SearchResult searchResult, JsonSerializer jsonSeri @Override public void setSemanticSearchResults(SearchResult searchResult, Double rerankerScore, - List captions) { - searchResult.setSemanticSearchResult(rerankerScore, captions); + List captions, Double rerankerBoostedScore) { + searchResult.setSemanticSearchResult(rerankerScore, captions, rerankerBoostedScore); } @Override @@ -184,8 +184,10 @@ private void setDocumentDebugInfo(DocumentDebugInfo documentDebugInfo) { * * @param rerankerScore The reranker score. * @param captions The captions. + * @param rerankerBoostedScore The boosted reranker score. */ - private void setSemanticSearchResult(Double rerankerScore, List captions) { - this.semanticSearch = new SemanticSearchResult(rerankerScore, captions); + private void setSemanticSearchResult(Double rerankerScore, List captions, + Double rerankerBoostedScore) { + this.semanticSearch = new SemanticSearchResult(rerankerScore, captions, rerankerBoostedScore); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResult.java index ff4a5179a3e3..f1890fbfda6c 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResult.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResult.java @@ -20,7 +20,15 @@ public final class SemanticSearchResult { */ private final List queryCaptions; - SemanticSearchResult(Double rerankerScore, List queryCaptions) { + /* + * The relevance score computed by boosting the Reranker Score. Search results are sorted by the + * RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the Semantic Config. + * RerankerBoostedScore is only returned for queries of type 'semantic' + */ + private final Double rerankerBoostedScore; + + SemanticSearchResult(Double rerankerScore, List queryCaptions, Double rerankerBoostedScore) { + this.rerankerBoostedScore = rerankerBoostedScore; this.rerankerScore = rerankerScore; this.queryCaptions = queryCaptions; } @@ -46,4 +54,16 @@ public Double getRerankerScore() { public List getQueryCaptions() { return this.queryCaptions; } + + /** + * Get the rerankerBoostedScore property: The relevance score computed by boosting the Reranker Score. Search + * results are sorted by the RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the + * Semantic Config. RerankerBoostedScore is only returned for queries of type 'semantic'. + * + * @return the rerankerBoostedScore value. + */ + public Double getRerankerBoostedScore() { + return this.rerankerBoostedScore; + } + } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java index 27b5eca80415..fdefb1cd3c4a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorQuery.java @@ -66,6 +66,13 @@ public class VectorQuery implements JsonSerializable { */ private String filterOverride; + /* + * Controls how many vectors can be matched from each document in a vector search query. Setting it to 1 ensures at + * most one vector per document is matched, guaranteeing results come from distinct documents. Setting it to 0 + * (unlimited) allows multiple relevant vectors from the same document to be matched. Default is 0. + */ + private Integer perDocumentVectorLimit; + /** * Creates an instance of VectorQuery class. */ @@ -243,6 +250,32 @@ public VectorQuery setFilterOverride(String filterOverride) { return this; } + /** + * Get the perDocumentVectorLimit property: Controls how many vectors can be matched from each document in a vector + * search query. Setting it to 1 ensures at most one vector per document is matched, guaranteeing results come from + * distinct documents. Setting it to 0 (unlimited) allows multiple relevant vectors from the same document to be + * matched. Default is 0. + * + * @return the perDocumentVectorLimit value. + */ + public Integer getPerDocumentVectorLimit() { + return this.perDocumentVectorLimit; + } + + /** + * Set the perDocumentVectorLimit property: Controls how many vectors can be matched from each document in a vector + * search query. Setting it to 1 ensures at most one vector per document is matched, guaranteeing results come from + * distinct documents. Setting it to 0 (unlimited) allows multiple relevant vectors from the same document to be + * matched. Default is 0. + * + * @param perDocumentVectorLimit the perDocumentVectorLimit value to set. + * @return the VectorQuery object itself. + */ + public VectorQuery setPerDocumentVectorLimit(Integer perDocumentVectorLimit) { + this.perDocumentVectorLimit = perDocumentVectorLimit; + return this; + } + /** * {@inheritDoc} */ @@ -257,6 +290,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNumberField("weight", this.weight); jsonWriter.writeJsonField("threshold", this.threshold); jsonWriter.writeStringField("filterOverride", this.filterOverride); + jsonWriter.writeNumberField("perDocumentVectorLimit", this.perDocumentVectorLimit); return jsonWriter.writeEndObject(); } @@ -322,6 +356,8 @@ static VectorQuery fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOEx deserializedVectorQuery.threshold = VectorThreshold.fromJson(reader); } else if ("filterOverride".equals(fieldName)) { deserializedVectorQuery.filterOverride = reader.getString(); + } else if ("perDocumentVectorLimit".equals(fieldName)) { + deserializedVectorQuery.perDocumentVectorLimit = reader.getNullable(JsonReader::getInt); } else { reader.skipChildren(); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java index bb9c1f2374f7..473bd8e85f4b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java @@ -129,6 +129,15 @@ public VectorizableImageBinaryQuery setFilterOverride(String filterOverride) { return this; } + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageBinaryQuery setPerDocumentVectorLimit(Integer perDocumentVectorLimit) { + super.setPerDocumentVectorLimit(perDocumentVectorLimit); + return this; + } + /** * {@inheritDoc} */ @@ -142,6 +151,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNumberField("weight", getWeight()); jsonWriter.writeJsonField("threshold", getThreshold()); jsonWriter.writeStringField("filterOverride", getFilterOverride()); + jsonWriter.writeNumberField("perDocumentVectorLimit", getPerDocumentVectorLimit()); jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); jsonWriter.writeStringField("base64Image", this.base64Image); return jsonWriter.writeEndObject(); @@ -176,6 +186,9 @@ public static VectorizableImageBinaryQuery fromJson(JsonReader jsonReader) throw deserializedVectorizableImageBinaryQuery.setThreshold(VectorThreshold.fromJson(reader)); } else if ("filterOverride".equals(fieldName)) { deserializedVectorizableImageBinaryQuery.setFilterOverride(reader.getString()); + } else if ("perDocumentVectorLimit".equals(fieldName)) { + deserializedVectorizableImageBinaryQuery + .setPerDocumentVectorLimit(reader.getNullable(JsonReader::getInt)); } else if ("kind".equals(fieldName)) { deserializedVectorizableImageBinaryQuery.kind = VectorQueryKind.fromString(reader.getString()); } else if ("base64Image".equals(fieldName)) { diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java index f1a5a23499ca..5bcfd48cae06 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java @@ -127,6 +127,15 @@ public VectorizableImageUrlQuery setFilterOverride(String filterOverride) { return this; } + /** + * {@inheritDoc} + */ + @Override + public VectorizableImageUrlQuery setPerDocumentVectorLimit(Integer perDocumentVectorLimit) { + super.setPerDocumentVectorLimit(perDocumentVectorLimit); + return this; + } + /** * {@inheritDoc} */ @@ -140,6 +149,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNumberField("weight", getWeight()); jsonWriter.writeJsonField("threshold", getThreshold()); jsonWriter.writeStringField("filterOverride", getFilterOverride()); + jsonWriter.writeNumberField("perDocumentVectorLimit", getPerDocumentVectorLimit()); jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); jsonWriter.writeStringField("url", this.url); return jsonWriter.writeEndObject(); @@ -174,6 +184,9 @@ public static VectorizableImageUrlQuery fromJson(JsonReader jsonReader) throws I deserializedVectorizableImageUrlQuery.setThreshold(VectorThreshold.fromJson(reader)); } else if ("filterOverride".equals(fieldName)) { deserializedVectorizableImageUrlQuery.setFilterOverride(reader.getString()); + } else if ("perDocumentVectorLimit".equals(fieldName)) { + deserializedVectorizableImageUrlQuery + .setPerDocumentVectorLimit(reader.getNullable(JsonReader::getInt)); } else if ("kind".equals(fieldName)) { deserializedVectorizableImageUrlQuery.kind = VectorQueryKind.fromString(reader.getString()); } else if ("url".equals(fieldName)) { diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java index 25c6b8af58f4..8d8a2f803063 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java @@ -145,6 +145,15 @@ public VectorizableTextQuery setFilterOverride(String filterOverride) { return this; } + /** + * {@inheritDoc} + */ + @Override + public VectorizableTextQuery setPerDocumentVectorLimit(Integer perDocumentVectorLimit) { + super.setPerDocumentVectorLimit(perDocumentVectorLimit); + return this; + } + /** * {@inheritDoc} */ @@ -158,6 +167,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNumberField("weight", getWeight()); jsonWriter.writeJsonField("threshold", getThreshold()); jsonWriter.writeStringField("filterOverride", getFilterOverride()); + jsonWriter.writeNumberField("perDocumentVectorLimit", getPerDocumentVectorLimit()); jsonWriter.writeStringField("text", this.text); jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); jsonWriter.writeStringField("queryRewrites", this.queryRewrites == null ? null : this.queryRewrites.toString()); @@ -182,6 +192,7 @@ public static VectorizableTextQuery fromJson(JsonReader jsonReader) throws IOExc Float weight = null; VectorThreshold threshold = null; String filterOverride = null; + Integer perDocumentVectorLimit = null; boolean textFound = false; String text = null; VectorQueryKind kind = VectorQueryKind.TEXT; @@ -203,6 +214,8 @@ public static VectorizableTextQuery fromJson(JsonReader jsonReader) throws IOExc threshold = VectorThreshold.fromJson(reader); } else if ("filterOverride".equals(fieldName)) { filterOverride = reader.getString(); + } else if ("perDocumentVectorLimit".equals(fieldName)) { + perDocumentVectorLimit = reader.getNullable(JsonReader::getInt); } else if ("text".equals(fieldName)) { text = reader.getString(); textFound = true; @@ -223,6 +236,7 @@ public static VectorizableTextQuery fromJson(JsonReader jsonReader) throws IOExc deserializedVectorizableTextQuery.setWeight(weight); deserializedVectorizableTextQuery.setThreshold(threshold); deserializedVectorizableTextQuery.setFilterOverride(filterOverride); + deserializedVectorizableTextQuery.setPerDocumentVectorLimit(perDocumentVectorLimit); deserializedVectorizableTextQuery.kind = kind; deserializedVectorizableTextQuery.queryRewrites = queryRewrites; return deserializedVectorizableTextQuery; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java index 3135f3aca958..844b899af583 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorizedQuery.java @@ -119,6 +119,15 @@ public VectorizedQuery setFilterOverride(String filterOverride) { return this; } + /** + * {@inheritDoc} + */ + @Override + public VectorizedQuery setPerDocumentVectorLimit(Integer perDocumentVectorLimit) { + super.setPerDocumentVectorLimit(perDocumentVectorLimit); + return this; + } + /** * {@inheritDoc} */ @@ -132,6 +141,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNumberField("weight", getWeight()); jsonWriter.writeJsonField("threshold", getThreshold()); jsonWriter.writeStringField("filterOverride", getFilterOverride()); + jsonWriter.writeNumberField("perDocumentVectorLimit", getPerDocumentVectorLimit()); jsonWriter.writeArrayField("vector", this.vector, (writer, element) -> writer.writeFloat(element)); jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); return jsonWriter.writeEndObject(); @@ -155,6 +165,7 @@ public static VectorizedQuery fromJson(JsonReader jsonReader) throws IOException Float weight = null; VectorThreshold threshold = null; String filterOverride = null; + Integer perDocumentVectorLimit = null; boolean vectorFound = false; List vector = null; VectorQueryKind kind = VectorQueryKind.VECTOR; @@ -175,6 +186,8 @@ public static VectorizedQuery fromJson(JsonReader jsonReader) throws IOException threshold = VectorThreshold.fromJson(reader); } else if ("filterOverride".equals(fieldName)) { filterOverride = reader.getString(); + } else if ("perDocumentVectorLimit".equals(fieldName)) { + perDocumentVectorLimit = reader.getNullable(JsonReader::getInt); } else if ("vector".equals(fieldName)) { vector = reader.readArray(reader1 -> reader1.getFloat()); vectorFound = true; @@ -193,6 +206,7 @@ public static VectorizedQuery fromJson(JsonReader jsonReader) throws IOException deserializedVectorizedQuery.setWeight(weight); deserializedVectorizedQuery.setThreshold(threshold); deserializedVectorizedQuery.setFilterOverride(filterOverride); + deserializedVectorizedQuery.setPerDocumentVectorLimit(perDocumentVectorLimit); deserializedVectorizedQuery.kind = kind; return deserializedVectorizedQuery; } diff --git a/sdk/search/azure-search-documents/src/samples/README.md b/sdk/search/azure-search-documents/src/samples/README.md index 6cdcb06c0a0d..47ba81320f0d 100644 --- a/sdk/search/azure-search-documents/src/samples/README.md +++ b/sdk/search/azure-search-documents/src/samples/README.md @@ -61,7 +61,7 @@ add the direct dependency to your project as follows. com.azure azure-search-documents - 11.8.0-beta.6 + 11.8.0-beta.7 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeAgentTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeAgentTests.java new file mode 100644 index 000000000000..432f7a6ebe55 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeAgentTests.java @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.test.TestMode; +import com.azure.core.test.TestProxyTestBase; +import com.azure.json.JsonProviders; +import com.azure.json.JsonReader; +import com.azure.search.documents.indexes.SearchIndexClient; +import com.azure.search.documents.indexes.SearchIndexClientBuilder; +import com.azure.search.documents.indexes.models.AzureOpenAIModelName; +import com.azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters; +import com.azure.search.documents.indexes.models.KnowledgeAgent; +import com.azure.search.documents.indexes.models.KnowledgeAgentAzureOpenAIModel; +import com.azure.search.documents.indexes.models.KnowledgeAgentModel; +import com.azure.search.documents.indexes.models.KnowledgeAgentTargetIndex; +import com.azure.search.documents.indexes.models.SearchIndex; +import com.azure.search.documents.indexes.models.SemanticConfiguration; +import com.azure.search.documents.indexes.models.SemanticField; +import com.azure.search.documents.indexes.models.SemanticPrioritizedFields; +import com.azure.search.documents.indexes.models.SemanticSearch; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import static com.azure.search.documents.TestHelpers.HOTEL_INDEX_NAME; +import static com.azure.search.documents.TestHelpers.loadResource; +import static com.azure.search.documents.TestHelpers.uploadDocumentsJson; +import static com.azure.search.documents.TestHelpers.waitForIndexing; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Execution(ExecutionMode.SAME_THREAD) +public class KnowledgeAgentTests extends SearchTestBase { + + private static final List KNOWLEDGE_AGENT_MODELS + = Collections.singletonList(new KnowledgeAgentAzureOpenAIModel( + new AzureOpenAIVectorizerParameters().setModelName(AzureOpenAIModelName.GPT4O) + .setDeploymentName("gpt-35-turbo") + .setApiKey(OPENAI_API_KEY) + .setResourceUrl(OPENAI_API_ENDPOINT))); + private static final List KNOWLEDGE_AGENT_TARGET_INDEX + = Collections.singletonList(new KnowledgeAgentTargetIndex(HOTEL_INDEX_NAME)); + + private static SearchIndexClient searchIndexClient; + + @BeforeAll + public static void setupClass() { + // Set up any necessary configurations or resources before all tests. + TestProxyTestBase.setupClass(); + + if (TEST_MODE == TestMode.PLAYBACK) { + return; + } + + searchIndexClient = setupIndex(); + + waitForIndexing(); + + } + + @AfterAll + protected static void cleanupClass() { + // Clean up any resources after all tests. + if (TEST_MODE != TestMode.PLAYBACK) { + // list all remaining knowledge agents and delete them + List knowledgeAgents + = searchIndexClient.listKnowledgeAgents().stream().collect(Collectors.toList()); + for (KnowledgeAgent knowledgeAgent : knowledgeAgents) { + searchIndexClient.deleteKnowledgeAgent(knowledgeAgent.getName(), null, null); + } + + searchIndexClient.deleteIndex(HOTEL_INDEX_NAME); + + try { + Thread.sleep(5000); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + } + } + + @Test + public void testCreateKnowledgeAgent() { + // Test creating a knowledge agent. + SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); + KnowledgeAgent knowledgeAgent + = new KnowledgeAgent(randomKnowledgeAgentName(), KNOWLEDGE_AGENT_MODELS, KNOWLEDGE_AGENT_TARGET_INDEX); + searchIndexClient.createKnowledgeAgent(knowledgeAgent); + } + + @Test + public void testGetKnowledgeAgent() { + // Test getting a knowledge agent. + + SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); + KnowledgeAgent knowledgeAgent + = new KnowledgeAgent(randomKnowledgeAgentName(), KNOWLEDGE_AGENT_MODELS, KNOWLEDGE_AGENT_TARGET_INDEX); + searchIndexClient.createKnowledgeAgent(knowledgeAgent); + KnowledgeAgent retrieved = searchIndexClient.getKnowledgeAgent(knowledgeAgent.getName()); + assertEquals(knowledgeAgent.getName(), retrieved.getName()); + } + + @Test + public void testListKnowledgeAgents() { + // Test listing knowledge agents. + SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); + long currentCount = searchIndexClient.listKnowledgeAgents().stream().count(); + KnowledgeAgent knowledgeAgent + = new KnowledgeAgent(randomKnowledgeAgentName(), KNOWLEDGE_AGENT_MODELS, KNOWLEDGE_AGENT_TARGET_INDEX); + KnowledgeAgent knowledgeAgent2 + = new KnowledgeAgent(randomKnowledgeAgentName(), KNOWLEDGE_AGENT_MODELS, KNOWLEDGE_AGENT_TARGET_INDEX); + searchIndexClient.createKnowledgeAgent(knowledgeAgent); + searchIndexClient.createKnowledgeAgent(knowledgeAgent2); + List knowledgeAgents + = searchIndexClient.listKnowledgeAgents().stream().collect(Collectors.toList()); + assertEquals(2 + currentCount, knowledgeAgents.size()); + } + + @Test + public void testDeleteKnowledgeAgent() { + // Test deleting a knowledge agent. + SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); + KnowledgeAgent knowledgeAgent + = new KnowledgeAgent(randomKnowledgeAgentName(), KNOWLEDGE_AGENT_MODELS, KNOWLEDGE_AGENT_TARGET_INDEX); + searchIndexClient.createKnowledgeAgent(knowledgeAgent); + waitForIndexing(); + assertNotNull(searchIndexClient.getKnowledgeAgent(knowledgeAgent.getName())); + searchIndexClient.deleteKnowledgeAgent(knowledgeAgent.getName(), null, null); + assertThrows(HttpResponseException.class, () -> searchIndexClient.getKnowledgeAgent(knowledgeAgent.getName())); + } + + @Test + public void testUpdateKnowledgeAgent() { + // Test updating a knowledge agent. + SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); + KnowledgeAgent knowledgeAgent + = new KnowledgeAgent(randomKnowledgeAgentName(), KNOWLEDGE_AGENT_MODELS, KNOWLEDGE_AGENT_TARGET_INDEX); + searchIndexClient.createKnowledgeAgent(knowledgeAgent); + String newDescription = "Updated description"; + knowledgeAgent.setDescription(newDescription); + searchIndexClient.createOrUpdateKnowledgeAgent(knowledgeAgent.getName(), knowledgeAgent, null, null); + KnowledgeAgent retrieved = searchIndexClient.getKnowledgeAgent(knowledgeAgent.getName()); + assertEquals(newDescription, retrieved.getDescription()); + } + + private String randomKnowledgeAgentName() { + // Generate a random name for the knowledge agent. + return testResourceNamer.randomName("knowledge-agent-", 63); + } + + private static SearchIndexClient setupIndex() { + try (JsonReader jsonReader = JsonProviders.createReader(loadResource(HOTELS_TESTS_INDEX_DATA_JSON))) { + SearchIndex baseIndex = SearchIndex.fromJson(jsonReader); + + SearchIndexClient searchIndexClient = new SearchIndexClientBuilder().endpoint(ENDPOINT) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .credential(TestHelpers.getTestTokenCredential()) + .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY) + .buildClient(); + + List semanticConfigurations + = Collections.singletonList(new SemanticConfiguration("semantic-config", + new SemanticPrioritizedFields().setTitleField(new SemanticField("HotelName")) + .setContentFields(new SemanticField("Description")) + .setKeywordsFields(new SemanticField("Category")))); + SemanticSearch semanticSearch = new SemanticSearch().setDefaultConfigurationName("semantic-config") + .setConfigurations(semanticConfigurations); + searchIndexClient.createOrUpdateIndex( + TestHelpers.createTestIndex(HOTEL_INDEX_NAME, baseIndex).setSemanticSearch(semanticSearch)); + + if (HOTELS_DATA_JSON != null) { + uploadDocumentsJson(searchIndexClient.getSearchClient(HOTEL_INDEX_NAME), HOTELS_DATA_JSON); + } + + return searchIndexClient; + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTestBase.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTestBase.java index 21df278225c8..c90f6e20eb5b 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTestBase.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTestBase.java @@ -82,6 +82,13 @@ public abstract class SearchTestBase extends TestProxyTestBase { protected static final String STORAGE_CONNECTION_STRING = Configuration.getGlobalConfiguration().get("SEARCH_STORAGE_CONNECTION_STRING", "connectionString"); + + protected static final String OPENAI_API_KEY + = Configuration.getGlobalConfiguration().get("AZURE_OPENAI_API_KEY", "your-api-key"); + + protected static final String OPENAI_API_ENDPOINT = Configuration.getGlobalConfiguration() + .get("AZURE_OPENAI_API_ENDPOINT", "https://your-endpoint.openai.azure.com"); + protected static final String BLOB_CONTAINER_NAME = "searchcontainer"; protected static final TestMode TEST_MODE = initializeTestMode(); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTests.java index b8ac7e8ef2fd..77c7cd09265d 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchTests.java @@ -612,7 +612,7 @@ public void canUseTopAndSkipForClientSidePagingAsync() { SearchOptions parameters = new SearchOptions().setTop(3).setSkip(0).setOrderBy("HotelId"); StepVerifier - .create(getSearchResultsAsync(asyncClient.search("*", parameters, Context.NONE)) + .create(getSearchResultsAsync(asyncClient.search("*", parameters, null, Context.NONE)) .map(docs -> docs.stream().map(sd -> sd.get("HotelId").toString()).collect(Collectors.toList()))) .assertNext(actualKeys -> assertEquals(Arrays.asList("1", "10", "2"), actualKeys)) .verifyComplete(); @@ -620,7 +620,7 @@ public void canUseTopAndSkipForClientSidePagingAsync() { parameters.setSkip(3); StepVerifier - .create(getSearchResultsAsync(asyncClient.search("*", parameters, Context.NONE)) + .create(getSearchResultsAsync(asyncClient.search("*", parameters, null, Context.NONE)) .map(docs -> docs.stream().map(sd -> sd.get("HotelId").toString()).collect(Collectors.toList()))) .assertNext(actualKeys -> assertEquals(Arrays.asList("3", "4", "5"), actualKeys)) .verifyComplete(); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourceTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourceTests.java index b8aff6deaaa7..d59e4e8835e5 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourceTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourceTests.java @@ -16,6 +16,8 @@ import com.azure.search.documents.indexes.models.SoftDeleteColumnDeletionDetectionPolicy; import com.azure.search.documents.indexes.models.SqlIntegratedChangeTrackingPolicy; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -44,6 +46,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +@Execution(ExecutionMode.SAME_THREAD) public class DataSourceTests extends SearchTestBase { private static final String FAKE_DESCRIPTION = "Some data source"; private static final String FAKE_STORAGE_CONNECTION_STRING diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexManagementTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexManagementTests.java index 0d067f905cef..628d9d38cc45 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexManagementTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexManagementTests.java @@ -28,6 +28,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; @@ -59,6 +61,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +@Execution(ExecutionMode.SAME_THREAD) public class IndexManagementTests extends SearchTestBase { private static SearchIndexClient sharedIndexClient; private static SynonymMap sharedSynonymMap; diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsetManagementTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsetManagementTests.java index 010305262cd8..541f9a9f6973 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsetManagementTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsetManagementTests.java @@ -38,6 +38,8 @@ import com.azure.search.documents.indexes.models.WebApiSkill; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; @@ -64,6 +66,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +@Execution(ExecutionMode.SAME_THREAD) public class SkillsetManagementTests extends SearchTestBase { private static final String CONTEXT_VALUE = "/document"; private static final String OCR_SKILLSET_NAME = "ocr-skillset"; diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SynonymMapManagementTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SynonymMapManagementTests.java index 1de043d6982d..3e7f3961b5b7 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SynonymMapManagementTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SynonymMapManagementTests.java @@ -12,6 +12,8 @@ import com.azure.search.documents.indexes.models.SynonymMap; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import reactor.util.function.Tuple2; @@ -36,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +@Execution(ExecutionMode.SAME_THREAD) public class SynonymMapManagementTests extends SearchTestBase { private final List synonymMapsToDelete = new ArrayList<>(); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/SearchRequestUrlRewriterPolicyTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/SearchRequestUrlRewriterPolicyTests.java index 1e4243eafb09..5e39a9edd430 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/SearchRequestUrlRewriterPolicyTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/SearchRequestUrlRewriterPolicyTests.java @@ -127,7 +127,7 @@ public static Stream correctUrlRewriteSupplier() { Arguments.of(toCallable(searchAsyncClient.getDocumentWithResponse("test", SearchDocument.class, null)), docsUrl + "/test"), Arguments.of(toCallable(searchAsyncClient.getDocumentCountWithResponse()), docsUrl + "/$count"), - Arguments.of(toCallable(searchAsyncClient.search("search", null)), docsUrl + "/search.post.search"), + Arguments.of(toCallable(searchAsyncClient.search("search", null, null)), docsUrl + "/search.post.search"), Arguments.of(toCallable(searchAsyncClient.suggest("suggest", "suggester", null)), docsUrl + "/search.post.suggest"), Arguments.of(toCallable(searchAsyncClient.autocomplete("autocomplete", "suggester", null)), diff --git a/sdk/search/azure-search-documents/swagger/README.md b/sdk/search/azure-search-documents/swagger/README.md index 19fc956ae9ce..f855c5a4e432 100644 --- a/sdk/search/azure-search-documents/swagger/README.md +++ b/sdk/search/azure-search-documents/swagger/README.md @@ -87,7 +87,7 @@ These settings apply only when `--tag=searchindex` is specified on the command l ``` yaml $(tag) == 'searchindex' namespace: com.azure.search.documents input-file: -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8c53aa7023e66a9ec24ede6a9fad0ed730d62515/specification/search/data-plane/Azure.Search/preview/2025-03-01-preview/searchindex.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/1755004c92eefdc7a66b4cd90df27d0af4cb0456/specification/search/data-plane/Azure.Search/preview/2025-05-01-preview/searchindex.json models-subpackage: models custom-types-subpackage: implementation.models custom-types: AutocompleteRequest,IndexAction,IndexBatch,RequestOptions,SearchDocumentsResult,SearchErrorException,SearchOptions,SearchRequest,SearchResult,SuggestDocumentsResult,SuggestRequest,SuggestResult,ErrorAdditionalInfo,ErrorDetail,ErrorResponse,ErrorResponseException,Speller @@ -105,7 +105,7 @@ These settings apply only when `--tag=searchservice` is specified on the command ``` yaml $(tag) == 'searchservice' namespace: com.azure.search.documents.indexes input-file: -- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/8c53aa7023e66a9ec24ede6a9fad0ed730d62515/specification/search/data-plane/Azure.Search/preview/2025-03-01-preview/searchservice.json +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/1755004c92eefdc7a66b4cd90df27d0af4cb0456/specification/search/data-plane/Azure.Search/preview/2025-05-01-preview/searchservice.json models-subpackage: models custom-types-subpackage: implementation.models custom-types: AnalyzeRequest,AnalyzeResult,AzureActiveDirectoryApplicationCredentials,DataSourceCredentials,DocumentKeysOrIds,EdgeNGramTokenFilterV1,EdgeNGramTokenFilterV2,EntityRecognitionSkillV1,EntityRecognitionSkillV3,KeywordTokenizerV1,KeywordTokenizerV2,ListAliasesResult,ListDataSourcesResult,ListIndexersResult,ListIndexesResult,ListSkillsetsResult,ListSynonymMapsResult,LuceneStandardTokenizerV1,LuceneStandardTokenizerV2,NGramTokenFilterV1,NGramTokenFilterV2,RequestOptions,SearchErrorException,SentimentSkillV1,SentimentSkillV3,SkillNames,ErrorAdditionalInfo,ErrorDetail,ErrorResponse,ErrorResponseException @@ -155,6 +155,19 @@ directive: to: SearchIndexerDataSourceConnection ``` +### Tag: knowledgeagent + +These settings apply only when `--tag=knowledgeagent` is specified on the commandSearchServiceCounters line. + +``` yaml $(tag) == 'knowledgeagent' +namespace: com.azure.search.documents.agents +input-file: +- https://raw.githubusercontent.com/Azure/azure-rest-api-specs/1755004c92eefdc7a66b4cd90df27d0af4cb0456/specification/search/data-plane/Azure.Search/preview/2025-05-01-preview/knowledgeagent.json +models-subpackage: models +custom-types-subpackage: implementation.models +custom-types: ErrorResponse,ErrorDetail,ErrorAdditionalInfo,ErrorResponseException,RequestOptions +``` + --- # Code Generation diff --git a/sdk/search/azure-search-documents/swagger/Update-Codegeneration.ps1 b/sdk/search/azure-search-documents/swagger/Update-Codegeneration.ps1 index d97b18f6df8c..6e74dd78c585 100644 --- a/sdk/search/azure-search-documents/swagger/Update-Codegeneration.ps1 +++ b/sdk/search/azure-search-documents/swagger/Update-Codegeneration.ps1 @@ -1,2 +1,3 @@ & (Join-Path $PSScriptRoot ".." ".." ".." ".." eng scripts Invoke-Codegeneration.ps1) -Directory $PSScriptRoot -AutorestOptions '--tag=searchindex' & (Join-Path $PSScriptRoot ".." ".." ".." ".." eng scripts Invoke-Codegeneration.ps1) -Directory $PSScriptRoot -AutorestOptions '--tag=searchservice' +& (Join-Path $PSScriptRoot ".." ".." ".." ".." eng scripts Invoke-Codegeneration.ps1) -Directory $PSScriptRoot -AutorestOptions '--tag=knowledgeagent'