// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
#nullable disable
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.AI.Language.Documents
{
///
/// The language service API is a suite of natural language processing (NLP) skills built with best-in-class Microsoft machine learning algorithms.
/// The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction, language detection and question answering.
/// Further documentation can be found in <a href=\"https://learn.microsoft.com/azure/cognitive-services/language-service/overview\">https://learn.microsoft.com/azure/cognitive-services/language-service/overview</a>.0
///
public partial class DocumentAnalysisClient
{
private readonly Uri _endpoint;
private const string AuthorizationHeader = "Ocp-Apim-Subscription-Key";
private static readonly string[] AuthorizationScopes = new string[] { "https://cognitiveservices.azure.com/.default" };
private readonly string _apiVersion;
/// Initializes a new instance of DocumentAnalysisClient for mocking.
protected DocumentAnalysisClient()
{
}
/// Initializes a new instance of DocumentAnalysisClient.
/// Supported Cognitive Services endpoint (e.g., https://<resource-name>.api.cognitiveservices.azure.com).
/// A credential used to authenticate to the service.
/// or is null.
/// is an empty string, and was expected to be non-empty.
public DocumentAnalysisClient(string endpoint, AzureKeyCredential credential) : this(endpoint, credential, new DocumentAnalysisClientOptions())
{
}
/// Initializes a new instance of DocumentAnalysisClient.
/// Supported Cognitive Services endpoint (e.g., https://<resource-name>.api.cognitiveservices.azure.com).
/// A credential used to authenticate to the service.
/// or is null.
/// is an empty string, and was expected to be non-empty.
public DocumentAnalysisClient(string endpoint, TokenCredential credential) : this(endpoint, credential, new DocumentAnalysisClientOptions())
{
}
/// Initializes a new instance of DocumentAnalysisClient.
/// The authentication policy to use for pipeline creation.
/// Supported Cognitive Services endpoint (e.g., https://<resource-name>.api.cognitiveservices.azure.com).
/// The options for configuring the client.
internal DocumentAnalysisClient(HttpPipelinePolicy authenticationPolicy, string endpoint, DocumentAnalysisClientOptions options)
{
Argument.AssertNotNullOrEmpty(endpoint, nameof(endpoint));
options ??= new DocumentAnalysisClientOptions();
_endpoint = new Uri($"{endpoint}/language");
if (authenticationPolicy != null)
{
Pipeline = HttpPipelineBuilder.Build(options, new HttpPipelinePolicy[] { authenticationPolicy });
}
else
{
Pipeline = HttpPipelineBuilder.Build(options, Array.Empty());
}
_apiVersion = options.Version;
ClientDiagnostics = new ClientDiagnostics(options, true);
}
/// Initializes a new instance of DocumentAnalysisClient.
/// Supported Cognitive Services endpoint (e.g., https://<resource-name>.api.cognitiveservices.azure.com).
/// A credential used to authenticate to the service.
/// The options for configuring the client.
/// or is null.
/// is an empty string, and was expected to be non-empty.
public DocumentAnalysisClient(string endpoint, AzureKeyCredential credential, DocumentAnalysisClientOptions options) : this(new AzureKeyCredentialPolicy(credential, AuthorizationHeader), endpoint, options)
{
}
/// Initializes a new instance of DocumentAnalysisClient.
/// Supported Cognitive Services endpoint (e.g., https://<resource-name>.api.cognitiveservices.azure.com).
/// A credential used to authenticate to the service.
/// The options for configuring the client.
/// or is null.
/// is an empty string, and was expected to be non-empty.
public DocumentAnalysisClient(string endpoint, TokenCredential credential, DocumentAnalysisClientOptions options) : this(new BearerTokenAuthenticationPolicy(credential, AuthorizationScopes), endpoint, options)
{
}
/// Initializes a new instance of DocumentAnalysisClient from a .
/// The settings for DocumentAnalysisClient.
[Experimental("SCME0002")]
public DocumentAnalysisClient(DocumentAnalysisClientSettings settings) : this(settings?.Endpoint, settings?.CredentialProvider as TokenCredential, settings?.Options)
{
}
/// The HTTP pipeline for sending and receiving REST requests and responses.
public virtual HttpPipeline Pipeline { get; }
/// The ClientDiagnostics is used to provide tracing support for the client library.
internal ClientDiagnostics ClientDiagnostics { get; }
///
/// [Protocol Method] Get the status of a document analysis job. A job can consist of one or more tasks. After all tasks succeed, the job transitions to the succeeded state and results are available for each task.
///
/// -
/// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios.
///
///
///
/// job ID.
/// (Optional) if set to true, response will contain request and document level statistics.
/// The maximum number of resources to return from the collection.
/// An offset into the collection of the first resource to be returned.
/// The request options, which can override default behaviors of the client pipeline on a per-call basis.
/// Service returned a non-success status code.
/// The response returned from the service.
public virtual Response GetAnalyzeDocumentsJobStatus(Guid jobId, bool? showStats, int? top, int? skip, RequestContext context)
{
using DiagnosticScope scope = ClientDiagnostics.CreateScope("DocumentAnalysisClient.GetAnalyzeDocumentsJobStatus");
scope.Start();
try
{
using HttpMessage message = CreateGetAnalyzeDocumentsJobStatusRequest(jobId, showStats, top, skip, context);
return Pipeline.ProcessMessage(message, context);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
///
/// [Protocol Method] Get the status of a document analysis job. A job can consist of one or more tasks. After all tasks succeed, the job transitions to the succeeded state and results are available for each task.
///
/// -
/// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios.
///
///
///
/// job ID.
/// (Optional) if set to true, response will contain request and document level statistics.
/// The maximum number of resources to return from the collection.
/// An offset into the collection of the first resource to be returned.
/// The request options, which can override default behaviors of the client pipeline on a per-call basis.
/// Service returned a non-success status code.
/// The response returned from the service.
public virtual async Task GetAnalyzeDocumentsJobStatusAsync(Guid jobId, bool? showStats, int? top, int? skip, RequestContext context)
{
using DiagnosticScope scope = ClientDiagnostics.CreateScope("DocumentAnalysisClient.GetAnalyzeDocumentsJobStatus");
scope.Start();
try
{
using HttpMessage message = CreateGetAnalyzeDocumentsJobStatusRequest(jobId, showStats, top, skip, context);
return await Pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// Get the status of a document analysis job. A job can consist of one or more tasks. After all tasks succeed, the job transitions to the succeeded state and results are available for each task.
/// job ID.
/// (Optional) if set to true, response will contain request and document level statistics.
/// The maximum number of resources to return from the collection.
/// An offset into the collection of the first resource to be returned.
/// The cancellation token that can be used to cancel the operation.
/// Service returned a non-success status code.
public virtual Response GetAnalyzeDocumentsJobStatus(Guid jobId, bool? showStats = default, int? top = default, int? skip = default, CancellationToken cancellationToken = default)
{
Response result = GetAnalyzeDocumentsJobStatus(jobId, showStats, top, skip, cancellationToken.ToRequestContext());
return Response.FromValue((AnalyzeDocumentsJobState)result, result);
}
/// Get the status of a document analysis job. A job can consist of one or more tasks. After all tasks succeed, the job transitions to the succeeded state and results are available for each task.
/// job ID.
/// (Optional) if set to true, response will contain request and document level statistics.
/// The maximum number of resources to return from the collection.
/// An offset into the collection of the first resource to be returned.
/// The cancellation token that can be used to cancel the operation.
/// Service returned a non-success status code.
public virtual async Task> GetAnalyzeDocumentsJobStatusAsync(Guid jobId, bool? showStats = default, int? top = default, int? skip = default, CancellationToken cancellationToken = default)
{
Response result = await GetAnalyzeDocumentsJobStatusAsync(jobId, showStats, top, skip, cancellationToken.ToRequestContext()).ConfigureAwait(false);
return Response.FromValue((AnalyzeDocumentsJobState)result, result);
}
/// Submit a collection of text documents for analysis. Specify one or more unique tasks to be executed as a long-running operation.
/// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples.
/// The content to send as the body of the request.
/// The request options, which can override default behaviors of the client pipeline on a per-call basis.
/// is null.
/// The response returned from the service.
public virtual Operation AnalyzeDocumentsSubmitOperation(WaitUntil waitUntil, RequestContent content, RequestContext context = null)
{
using DiagnosticScope scope = ClientDiagnostics.CreateScope("DocumentAnalysisClient.AnalyzeDocumentsSubmitOperation");
scope.Start();
try
{
Argument.AssertNotNull(content, nameof(content));
using HttpMessage message = CreateAnalyzeDocumentsSubmitOperationRequest(content, context);
return ProtocolOperationHelpers.ProcessMessage(Pipeline, message, ClientDiagnostics, "DocumentAnalysisClient.AnalyzeDocumentsSubmitOperation", OperationFinalStateVia.OperationLocation, context, waitUntil);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// Submit a collection of text documents for analysis. Specify one or more unique tasks to be executed as a long-running operation.
/// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples.
/// The content to send as the body of the request.
/// The request options, which can override default behaviors of the client pipeline on a per-call basis.
/// is null.
/// The response returned from the service.
public virtual async Task AnalyzeDocumentsSubmitOperationAsync(WaitUntil waitUntil, RequestContent content, RequestContext context = null)
{
using DiagnosticScope scope = ClientDiagnostics.CreateScope("DocumentAnalysisClient.AnalyzeDocumentsSubmitOperation");
scope.Start();
try
{
Argument.AssertNotNull(content, nameof(content));
using HttpMessage message = CreateAnalyzeDocumentsSubmitOperationRequest(content, context);
return await ProtocolOperationHelpers.ProcessMessageAsync(Pipeline, message, ClientDiagnostics, "DocumentAnalysisClient.AnalyzeDocumentsSubmitOperationAsync", OperationFinalStateVia.OperationLocation, context, waitUntil).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// Submit a collection of text documents for analysis. Specify one or more unique tasks to be executed as a long-running operation.
/// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples.
/// The input for the analyze documents operation.
/// The cancellation token that can be used to cancel the operation.
/// is null.
public virtual Operation AnalyzeDocumentsSubmitOperation(WaitUntil waitUntil, AnalyzeDocumentsOperationInput analyzeDocumentOperationInput, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(analyzeDocumentOperationInput, nameof(analyzeDocumentOperationInput));
return AnalyzeDocumentsSubmitOperation(waitUntil, analyzeDocumentOperationInput, cancellationToken.ToRequestContext());
}
/// Submit a collection of text documents for analysis. Specify one or more unique tasks to be executed as a long-running operation.
/// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples.
/// The input for the analyze documents operation.
/// The cancellation token that can be used to cancel the operation.
/// is null.
public virtual async Task AnalyzeDocumentsSubmitOperationAsync(WaitUntil waitUntil, AnalyzeDocumentsOperationInput analyzeDocumentOperationInput, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(analyzeDocumentOperationInput, nameof(analyzeDocumentOperationInput));
return await AnalyzeDocumentsSubmitOperationAsync(waitUntil, analyzeDocumentOperationInput, cancellationToken.ToRequestContext()).ConfigureAwait(false);
}
/// Cancel a long-running Text Analysis job.
/// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples.
/// The job ID to cancel.
/// The request options, which can override default behaviors of the client pipeline on a per-call basis.
/// The response returned from the service.
public virtual Operation AnalyzeDocumentsCancelOperation(WaitUntil waitUntil, Guid jobId, RequestContext context)
{
using DiagnosticScope scope = ClientDiagnostics.CreateScope("DocumentAnalysisClient.AnalyzeDocumentsCancelOperation");
scope.Start();
try
{
using HttpMessage message = CreateAnalyzeDocumentsCancelOperationRequest(jobId, context);
return ProtocolOperationHelpers.ProcessMessage(Pipeline, message, ClientDiagnostics, "DocumentAnalysisClient.AnalyzeDocumentsCancelOperation", OperationFinalStateVia.OperationLocation, context, waitUntil);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// Cancel a long-running Text Analysis job.
/// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples.
/// The job ID to cancel.
/// The request options, which can override default behaviors of the client pipeline on a per-call basis.
/// The response returned from the service.
public virtual async Task AnalyzeDocumentsCancelOperationAsync(WaitUntil waitUntil, Guid jobId, RequestContext context)
{
using DiagnosticScope scope = ClientDiagnostics.CreateScope("DocumentAnalysisClient.AnalyzeDocumentsCancelOperation");
scope.Start();
try
{
using HttpMessage message = CreateAnalyzeDocumentsCancelOperationRequest(jobId, context);
return await ProtocolOperationHelpers.ProcessMessageAsync(Pipeline, message, ClientDiagnostics, "DocumentAnalysisClient.AnalyzeDocumentsCancelOperationAsync", OperationFinalStateVia.OperationLocation, context, waitUntil).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// Cancel a long-running Text Analysis job.
/// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples.
/// The job ID to cancel.
/// The cancellation token that can be used to cancel the operation.
public virtual Operation AnalyzeDocumentsCancelOperation(WaitUntil waitUntil, Guid jobId, CancellationToken cancellationToken = default)
{
return AnalyzeDocumentsCancelOperation(waitUntil, jobId, cancellationToken.ToRequestContext());
}
/// Cancel a long-running Text Analysis job.
/// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples.
/// The job ID to cancel.
/// The cancellation token that can be used to cancel the operation.
public virtual async Task AnalyzeDocumentsCancelOperationAsync(WaitUntil waitUntil, Guid jobId, CancellationToken cancellationToken = default)
{
return await AnalyzeDocumentsCancelOperationAsync(waitUntil, jobId, cancellationToken.ToRequestContext()).ConfigureAwait(false);
}
}
}