|
| 1 | +# Azure Cognitive Language Services Text client library for .NET |
| 2 | + |
| 3 | +Text Analytics is part of the Azure Cognitive Service for Language, a cloud-based service that provides Natural Language Processing (NLP) features for understanding and analyzing text. This client library offers the following features: |
| 4 | + |
| 5 | +* Language detection |
| 6 | +* Sentiment analysis |
| 7 | +* Key phrase extraction |
| 8 | +* Named entity recognition (NER) |
| 9 | +* Personally identifiable information (PII) entity recognition |
| 10 | +* Entity linking |
| 11 | +* Text analytics for health |
| 12 | +* Custom named entity recognition (Custom NER) |
| 13 | +* Custom text classification |
| 14 | +* Extractive text summarization |
| 15 | +* Abstractive text summarization |
| 16 | + |
| 17 | + [Source code][source_root] | [Package (NuGet)][package]| [API reference documentation][text_refdocs] | [Product documentation][text_docs] | [Samples][source_samples] |
| 18 | + |
| 19 | +## Getting started |
| 20 | + |
| 21 | +### Install the package |
| 22 | + |
| 23 | +Install the client library for .NET with [NuGet](https://www.nuget.org/ ): |
| 24 | + |
| 25 | +```dotnetcli |
| 26 | +dotnet add package Azure.AI.Language.Text |
| 27 | +``` |
| 28 | + |
| 29 | +### Prerequisites |
| 30 | + |
| 31 | +* An [Azure subscription][azure_sub]. |
| 32 | +* An existing Cognitive Services or Language service resource. |
| 33 | + |
| 34 | +### Authenticate the client |
| 35 | + |
| 36 | +In order to interact with the Text service, you'll need to create an instance of the [`TextAnalysisClient`][textanalysisclient_class] class. You will need an **endpoint**, and an **API key** to instantiate a client object. For more information regarding authenticating with Cognitive Services, see [Authenticate requests to Azure Cognitive Services][cognitive_auth]. |
| 37 | + |
| 38 | +#### Get an API key |
| 39 | + |
| 40 | +You can get the `endpoint` and `API key` from the Cognitive Services resource or Language service resource information in the [Azure Portal][azure_portal]. |
| 41 | + |
| 42 | +Alternatively, use the [Azure CLI][azure_cli] snippet below to get the API key from the Language service resource. |
| 43 | + |
| 44 | +```PowerShell |
| 45 | +az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name> |
| 46 | +``` |
| 47 | + |
| 48 | +#### Create a TextAnalysisClient |
| 49 | + |
| 50 | +To use the `TextAnalysisClient`, use the following namespace in addition to those above, if needed. |
| 51 | + |
| 52 | +```C# Snippet:TextAnalysisClient_Namespace |
| 53 | +using Azure.AI.Language.Text; |
| 54 | +``` |
| 55 | + |
| 56 | +With your **endpoint** and **API key**, you can instantiate a `TextAnalysisClient`: |
| 57 | + |
| 58 | +```C# Snippet:CreateTextClient |
| 59 | +Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com"); |
| 60 | +AzureKeyCredential credential = new("your apikey"); |
| 61 | +TextAnalysisClient client = new TextAnalysisClient(endpoint, credential); |
| 62 | +``` |
| 63 | + |
| 64 | +#### Create a client using Azure Active Directory authentication |
| 65 | + |
| 66 | +You can also create a `TextAnalysisClient` using Azure Active Directory (AAD) authentication. Your user or service principal must be assigned the "Cognitive Services Language Reader" role. |
| 67 | +Using the [DefaultAzureCredential] you can authenticate a service using Managed Identity or a service principal, authenticate as a developer working on an application, and more all without changing code. |
| 68 | + |
| 69 | +Before you can use the `DefaultAzureCredential`, or any credential type from [Azure.Identity][azure_identity], you'll first need to [install the Azure.Identity package][azure_identity_install]. |
| 70 | + |
| 71 | +To use `DefaultAzureCredential` with a client ID and secret, you'll need to set the `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, and `AZURE_CLIENT_SECRET` environment variables; alternatively, you can pass those values |
| 72 | +to the `ClientSecretCredential` also in Azure.Identity. |
| 73 | + |
| 74 | +Make sure you use the right namespace for `DefaultAzureCredential` at the top of your source file: |
| 75 | + |
| 76 | +```C# Snippet:Text_Identity_Namespace |
| 77 | +using Azure.Identity; |
| 78 | +``` |
| 79 | + |
| 80 | +Then you can create an instance of `DefaultAzureCredential` and pass it to a new instance of your client: |
| 81 | + |
| 82 | +```C# Snippet:TextAnalysisClient_CreateWithDefaultAzureCredential |
| 83 | +Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com"); |
| 84 | +DefaultAzureCredential credential = new DefaultAzureCredential(); |
| 85 | +TextAnalysisClient client = new TextAnalysisClient(endpoint, credential); |
| 86 | +``` |
| 87 | + |
| 88 | +Note that regional endpoints do not support AAD authentication. Instead, create a [custom domain][custom_domain] name for your resource to use AAD authentication. |
| 89 | + |
| 90 | +### Service API versions |
| 91 | + |
| 92 | +The client library targets the latest service API version by default. A client instance accepts an optional service API version parameter from its options to specify which API version service to communicate. |
| 93 | + |
| 94 | +#### Select a service API version |
| 95 | + |
| 96 | +You have the flexibility to explicitly select a supported service API version when instantiating a client by configuring its associated options. This ensures that the client can communicate with services using the specified API version. |
| 97 | + |
| 98 | +For example, |
| 99 | + |
| 100 | +```C# Snippet:CreateTextAnalysisClientForSpecificApiVersion |
| 101 | +Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com"); |
| 102 | +AzureKeyCredential credential = new("your apikey"); |
| 103 | +TextAnalysisClientOptions options = new TextAnalysisClientOptions(TextAnalysisClientOptions.ServiceVersion.V2023_04_01); |
| 104 | +var client = new TextAnalysisClient(endpoint, credential, options); |
| 105 | +``` |
| 106 | + |
| 107 | +When selecting an API version, it's important to verify that there are no breaking changes compared to the latest API version. If there are significant differences, API calls may fail due to incompatibility. |
| 108 | + |
| 109 | +Always ensure that the chosen API version is fully supported and operational for your specific use case and that it aligns with the service's versioning policy. |
| 110 | + |
| 111 | +## Key concepts |
| 112 | + |
| 113 | +### TextAnalysisClient |
| 114 | + |
| 115 | +The [`TextAnalysisClient`][textanalysisclient_class] is the primary interface for developers using the Azure AI Text client library. It provides both synchronous and asynchronous operations to access a specific use of text analysis, such as language detection or key phrase extraction. |
| 116 | + |
| 117 | +### Thread safety |
| 118 | + |
| 119 | +We guarantee that all client instance methods are thread-safe and independent of each other ([guideline](https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-service-methods-thread-safety)). This ensures that the recommendation of reusing client instances is always safe, even across threads. |
| 120 | + |
| 121 | +### Additional concepts |
| 122 | +<!-- CLIENT COMMON BAR --> |
| 123 | +[Client options](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#configuring-service-clients-using-clientoptions) | |
| 124 | +[Accessing the response](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#accessing-http-response-details-using-responset) | |
| 125 | +[Long-running operations](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#consuming-long-running-operations-using-operationt) | |
| 126 | +[Handling failures](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#reporting-errors-requestfailedexception) | |
| 127 | +[Diagnostics](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md) | |
| 128 | +[Mocking](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#mocking) | |
| 129 | +[Client lifetime](https://devblogs.microsoft.com/azure-sdk/lifetime-management-and-thread-safety-guarantees-of-azure-sdk-net-clients/) |
| 130 | +<!-- CLIENT COMMON BAR --> |
| 131 | + |
| 132 | +## Examples |
| 133 | + |
| 134 | +You can familiarize yourself with different APIs using [Samples](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples). |
| 135 | + |
| 136 | +* [Detect Language](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample1_AnalyzeText_LanguageDetection.md) |
| 137 | +* [Analyze Sentiment](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample2_AnalyzeText_Sentiment.md) |
| 138 | +* [Extract Key Phrases](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample3_AnalyzeText_ExtractKeyPhrases.md) |
| 139 | +* [Recognize Named Entities](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample4_AnalyzeText_RecognizeEntities.md) |
| 140 | +* [Recognize PII Entities](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample5_AnalyzeText_RecognizePiiEntities.md) |
| 141 | +* [Recognize Linked Entities](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample6_AnalyzeText_RecognizeLinkedEntities.md) |
| 142 | +* [Analyze Healthcare Entities](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample7_AnalyzeTextOperation_HealthcareOperationAction.md) |
| 143 | +* [Custom Named Entity Recognition](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample8_AnalyzeTextOperation_CustomEntitiesOperationAction.md) |
| 144 | +* [Custom Single Label Classification](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample9_AnalyzeTextOperation_CustomSingleLabelClassificationOperationAction.md) |
| 145 | +* [Custom Multi Label Classification](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample10_AnalyzeTextOperation_CustomMultiLabelClassificationOperationAction.md) |
| 146 | +* [Extractive Summarization](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample11_AnalyzeTextOperation_ExtractiveSummarizationOperationAction.md) |
| 147 | +* [Abstractive Summarization](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample12_AnalyzeTextOperation_AbstractiveSummarizationOperationAction.md) |
| 148 | +* [Perform multiple text analysis actions](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples/Sample13_AnalyzeTextOperation_MultipleActions.md) |
| 149 | + |
| 150 | +## Troubleshooting |
| 151 | + |
| 152 | +### General |
| 153 | + |
| 154 | +When you interact with the Cognitive Language Services Text client library using the .NET SDK, errors returned by the service correspond to the same HTTP status codes returned for REST API requests. |
| 155 | + |
| 156 | +For example, if you submit a utterance to a non-existant project, a `400` error is returned indicating "Bad Request". |
| 157 | + |
| 158 | +```C# Snippet:TextAnalysisClient_BadRequest |
| 159 | +try |
| 160 | +{ |
| 161 | + string textA = |
| 162 | + "We love this trail and make the trip every year. The views are breathtaking and well worth the hike!" |
| 163 | + + " Yesterday was foggy though, so we missed the spectacular views. We tried again today and it was" |
| 164 | + + " amazing. Everyone in my family liked the trail although it was too challenging for the less" |
| 165 | + + " athletic among us. Not necessarily recommended for small children. A hotel close to the trail" |
| 166 | + + " offers services for childcare in case you want that."; |
| 167 | + |
| 168 | + AnalyzeTextInput body = new TextEntityRecognitionInput() |
| 169 | + { |
| 170 | + TextInput = new MultiLanguageTextInput() |
| 171 | + { |
| 172 | + MultiLanguageInputs = |
| 173 | + { |
| 174 | + new MultiLanguageInput("D", textA), |
| 175 | + } |
| 176 | + }, |
| 177 | + ActionContent = new EntitiesActionContent() |
| 178 | + { |
| 179 | + ModelVersion = "NotValid", // Invalid model version will is a bad request. |
| 180 | + } |
| 181 | + }; |
| 182 | + |
| 183 | + Response<AnalyzeTextResult> response = client.AnalyzeText(body); |
| 184 | +} |
| 185 | +catch (RequestFailedException ex) |
| 186 | +{ |
| 187 | + Console.WriteLine(ex.ToString()); |
| 188 | +} |
| 189 | +``` |
| 190 | + |
| 191 | +You will notice that additional information is logged, like the client request ID of the operation. |
| 192 | + |
| 193 | +```text |
| 194 | +Azure.RequestFailedException: The input parameter is invalid. |
| 195 | +Status: 400 (Bad Request) |
| 196 | +ErrorCode: InvalidArgument |
| 197 | +
|
| 198 | +Content: |
| 199 | +Azure.RequestFailedException: Invalid Request. |
| 200 | +Status: 400 (Bad Request) |
| 201 | +ErrorCode: InvalidRequest |
| 202 | +
|
| 203 | +Content: |
| 204 | +{"error":{"code":"InvalidRequest","message":"Invalid Request.","innererror":{"code":"ModelVersionIncorrect","message":"Invalid model version. Possible values are: latest,2021-06-01,2023-09-01,2024-05-01. For additional details see https://aka.ms/text-analytics-model-versioning"}}} |
| 205 | +
|
| 206 | +Headers: |
| 207 | +Transfer-Encoding: chunked |
| 208 | +x-envoy-upstream-service-time: REDACTED |
| 209 | +apim-request-id: REDACTED |
| 210 | +Strict-Transport-Security: REDACTED |
| 211 | +X-Content-Type-Options: REDACTED |
| 212 | +x-ms-region: REDACTED |
| 213 | +Date: Wed, 24 Jul 2024 13:39:00 GMT |
| 214 | +Content-Type: application/json; charset=utf-8 |
| 215 | +``` |
| 216 | + |
| 217 | +### Setting up console logging |
| 218 | + |
| 219 | +The simplest way to see the logs is to enable the console logging. |
| 220 | +To create an Azure SDK log listener that outputs messages to console use AzureEventSourceListener.CreateConsoleLogger method. |
| 221 | + |
| 222 | +```C# |
| 223 | +// Setup a listener to monitor logged events. |
| 224 | +using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(); |
| 225 | +``` |
| 226 | + |
| 227 | +To learn more about other logging mechanisms see [here][logging]. |
| 228 | + |
| 229 | +## Next steps |
| 230 | + |
| 231 | +* View our [samples][source_samples]. |
| 232 | +* Read about the different [features][text_docs] of the Text service. |
| 233 | + |
| 234 | +## Contributing |
| 235 | + |
| 236 | +See the [CONTRIBUTING.md][contributing] for details on building, testing, and contributing to this library. |
| 237 | + |
| 238 | +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla.microsoft.com][cla]. |
| 239 | + |
| 240 | +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. |
| 241 | + |
| 242 | +This project has adopted the [Microsoft Open Source Code of Conduct ][code_of_conduct]. For more information see the [Code of Conduct FAQ ][coc_faq] or contact [[email protected]][coc_contact] with any additional questions or comments. |
| 243 | + |
| 244 | + |
| 245 | +<!-- LINKS --> |
| 246 | +[contributing]: https://github.com/Azure/azure-sdk-for-net/blob/main/CONTRIBUTING.md |
| 247 | +[cla]: https://cla.microsoft.com |
| 248 | +[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ |
| 249 | +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ |
| 250 | +[coc_contact]: mailto:[email protected] |
| 251 | +[DefaultAzureCredential]: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/README.md#defaultazurecredential |
| 252 | +[azure_identity]: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/README.md |
| 253 | +[azure_identity_install]: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/README.md#install-the-package |
| 254 | +[custom_domain]: https://docs.microsoft.com/azure/cognitive-services/authentication#create-a-resource-with-a-custom-subdomain |
| 255 | +[source_samples]: https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/cognitivelanguage/Azure.AI.Language.Text/samples |
| 256 | +[source_root]: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/cognitivelanguage/Azure.AI.Language.Text/src |
| 257 | +[package]: https://www.nuget.org/packages/ <!-- need to update link when nuget published --> |
| 258 | +[text_refdocs]: https://learn.microsoft.com/dotnet/ <!-- need to update link when docs are published --> |
| 259 | +[text_docs]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/ |
| 260 | +[azure_sub]: https://azure.microsoft.com/free/dotnet/ |
| 261 | +[textanalysisclient_class]: https://github.com/azure/azure-sdk-for-net/blob/main/sdk/cognitivelanguage/Azure.AI.Language.Text/src/TextAnalysisClient.cs |
| 262 | +[cognitive_auth]: https://docs.microsoft.com/azure/cognitive-services/authentication/ |
| 263 | +[azure_cli]: https://docs.microsoft.com/cli/azure |
| 264 | +[azure_portal]: https://portal.azure.com |
| 265 | +[logging]: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md |
| 266 | + |
0 commit comments