@azure/ai-language-text 1.0.0-alpha.20220808.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +780 -0
  3. package/dist/index.js +4771 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist-esm/src/azureKeyCredentialPolicy.js +22 -0
  6. package/dist-esm/src/azureKeyCredentialPolicy.js.map +1 -0
  7. package/dist-esm/src/constants.js +16 -0
  8. package/dist-esm/src/constants.js.map +1 -0
  9. package/dist-esm/src/generated/generatedClient.js +119 -0
  10. package/dist-esm/src/generated/generatedClient.js.map +1 -0
  11. package/dist-esm/src/generated/index.js +11 -0
  12. package/dist-esm/src/generated/index.js.map +1 -0
  13. package/dist-esm/src/generated/models/index.js +644 -0
  14. package/dist-esm/src/generated/models/index.js.map +1 -0
  15. package/dist-esm/src/generated/models/mappers.js +2810 -0
  16. package/dist-esm/src/generated/models/mappers.js.map +1 -0
  17. package/dist-esm/src/generated/models/parameters.js +98 -0
  18. package/dist-esm/src/generated/models/parameters.js.map +1 -0
  19. package/dist-esm/src/generated/operations/analyzeText.js +105 -0
  20. package/dist-esm/src/generated/operations/analyzeText.js.map +1 -0
  21. package/dist-esm/src/generated/operations/index.js +9 -0
  22. package/dist-esm/src/generated/operations/index.js.map +1 -0
  23. package/dist-esm/src/generated/operationsInterfaces/analyzeText.js +9 -0
  24. package/dist-esm/src/generated/operationsInterfaces/analyzeText.js.map +1 -0
  25. package/dist-esm/src/generated/operationsInterfaces/index.js +9 -0
  26. package/dist-esm/src/generated/operationsInterfaces/index.js.map +1 -0
  27. package/dist-esm/src/index.js +18 -0
  28. package/dist-esm/src/index.js.map +1 -0
  29. package/dist-esm/src/logger.js +9 -0
  30. package/dist-esm/src/logger.js.map +1 -0
  31. package/dist-esm/src/lro.js +179 -0
  32. package/dist-esm/src/lro.js.map +1 -0
  33. package/dist-esm/src/models.js +42 -0
  34. package/dist-esm/src/models.js.map +1 -0
  35. package/dist-esm/src/textAnalysisClient.js +191 -0
  36. package/dist-esm/src/textAnalysisClient.js.map +1 -0
  37. package/dist-esm/src/transforms.js +287 -0
  38. package/dist-esm/src/transforms.js.map +1 -0
  39. package/dist-esm/src/util.js +117 -0
  40. package/dist-esm/src/util.js.map +1 -0
  41. package/package.json +135 -0
  42. package/types/ai-language-text.d.ts +2477 -0
package/README.md ADDED
@@ -0,0 +1,780 @@
1
+ # Azure Text Analysis client library for JavaScript
2
+
3
+ [Azure Cognitive Service for Language](https://azure.microsoft.com/services/cognitive-services/language-service/) is a cloud-based service that provides advanced natural language processing over raw text, and includes the following main features:
4
+
5
+ **Note:** This SDK targets Azure Cognitive Service for Language API version 2022-04-01-preview.
6
+
7
+ - Language Detection
8
+ - Sentiment Analysis
9
+ - Key Phrase Extraction
10
+ - Named Entity Recognition
11
+ - Recognition of Personally Identifiable Information
12
+ - Entity Linking
13
+ - Healthcare Analysis
14
+ - Extractive Summarization
15
+ - Custom Entity Recognition
16
+ - Custom Document Classification
17
+ - Support Multiple Actions Per Document
18
+
19
+ Use the client library to:
20
+
21
+ - Detect what language input text is written in.
22
+ - Determine what customers think of your brand or topic by analyzing raw text for clues about positive or negative sentiment.
23
+ - Automatically extract key phrases to quickly identify the main points.
24
+ - Identify and categorize entities in your text as people, places, organizations, date/time, quantities, percentages, currencies, healthcare specific, and more.
25
+ - Perform multiple of the above tasks at once.
26
+
27
+ Key links:
28
+
29
+ - [Source code](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/cognitivelanguage/ai-language-text/)
30
+ - Package (NPM) (TODO)
31
+ - API reference documentation (TODO)
32
+ - [Product documentation](https://docs.microsoft.com/azure/cognitive-services/language-service/)
33
+ - [Samples](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/cognitivelanguage/ai-language-text/samples-dev)
34
+
35
+ ## Getting started
36
+
37
+ ### Currently supported environments
38
+
39
+ - [LTS versions of Node.js](https://nodejs.org/about/releases/)
40
+ - Latest versions of Safari, Chrome, Edge, and Firefox.
41
+
42
+ See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details.
43
+
44
+ ### Prerequisites
45
+
46
+ - An [Azure subscription][azure_sub].
47
+ - An existing [Cognitive Services][cognitive_resource] or Language resource. If you need to create the resource, you can use the [Azure Portal][azure_portal] or [Azure CLI][azure_cli].
48
+
49
+ If you use the Azure CLI, replace `<your-resource-group-name>` and `<your-resource-name>` with your own unique names:
50
+
51
+ ```PowerShell
52
+ az cognitiveservices account create --kind TextAnalytics --resource-group <your-resource-group-name> --name <your-resource-name> --sku <your-sku-name> --location <your-location>
53
+ ```
54
+
55
+ ### Install the `@azure/ai-language-text` package
56
+
57
+ Install the Azure Text Analysis client library for JavaScript with `npm`:
58
+
59
+ ```bash
60
+ npm install @azure/ai-language-text
61
+ ```
62
+
63
+ ### Create and authenticate a `TextAnalysisClient`
64
+
65
+ To create a client object to access the Language API, you will need the `endpoint` of your Language resource and a `credential`. The Text Analysis client can use either Azure Active Directory credentials or an API key credential to authenticate.
66
+
67
+ You can find the endpoint for your Language resource either in the [Azure Portal][azure_portal] or by using the [Azure CLI][azure_cli] snippet below:
68
+
69
+ ```bash
70
+ az cognitiveservices account show --name <your-resource-name> --resource-group <your-resource-group-name> --query "properties.endpoint"
71
+ ```
72
+
73
+ #### Using an API Key
74
+
75
+ Use the [Azure Portal][azure_portal] to browse to your Language resource and retrieve an API key, or use the [Azure CLI][azure_cli] snippet below:
76
+
77
+ **Note:** Sometimes the API key is referred to as a "subscription key" or "subscription API key."
78
+
79
+ ```PowerShell
80
+ az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>
81
+ ```
82
+
83
+ Once you have an API key and endpoint, you can use the `AzureKeyCredential` class to authenticate the client as follows:
84
+
85
+ ```javascript
86
+ const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");
87
+
88
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
89
+ ```
90
+
91
+ #### Using an Azure Active Directory Credential
92
+
93
+ Client API key authentication is used in most of the examples, but you can also authenticate with Azure Active Directory using the [Azure Identity library][azure_identity]. To use the [DefaultAzureCredential][defaultazurecredential] provider shown below,
94
+ or other credential providers provided with the Azure SDK, please install the `@azure/identity` package:
95
+
96
+ ```bash
97
+ npm install @azure/identity
98
+ ```
99
+
100
+ You will also need to [register a new AAD application][register_aad_app] and grant access to Language by assigning the `"Cognitive Services User"` role to your service principal (note: other roles such as `"Owner"` will not grant the necessary permissions, only `"Cognitive Services User"` will suffice to run the examples and the sample code).
101
+
102
+ Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET`.
103
+
104
+ ```javascript
105
+ const { TextAnalysisClient } = require("@azure/ai-language-text");
106
+ const { DefaultAzureCredential } = require("@azure/identity");
107
+
108
+ const client = new TextAnalysisClient("<endpoint>", new DefaultAzureCredential());
109
+ ```
110
+
111
+ ## Key concepts
112
+
113
+ ### TextAnalysisClient
114
+
115
+ `TextAnalysisClient` is the primary interface for developers using the Text Analysis client library. Explore the methods on this client object to understand the different features of the Language service that you can access.
116
+
117
+ ### Input
118
+
119
+ A **document** represents a single unit of input to be analyzed by the predictive models in the Language service. Operations on `TextAnalysisClient` take a collection of inputs to be analyzed as a batch. The operation methods have overloads that allow the inputs to be represented as strings, or as objects with attached metadata.
120
+
121
+ For example, each document can be passed as a string in an array, e.g.
122
+
123
+ ```typescript
124
+ const documents = [
125
+ "I hated the movie. It was so slow!",
126
+ "The movie made it into my top ten favorites.",
127
+ "What a great movie!",
128
+ ];
129
+ ```
130
+
131
+ or, if you wish to pass in a per-item document `id` or `language`/`countryHint`, they can be given as a list of `TextDocumentInput` or `DetectLanguageInput` depending on the operation;
132
+
133
+ ```javascript
134
+ const textDocumentInputs = [
135
+ { id: "1", language: "en", text: "I hated the movie. It was so slow!" },
136
+ { id: "2", language: "en", text: "The movie made it into my top ten favorites." },
137
+ { id: "3", language: "en", text: "What a great movie!" },
138
+ ];
139
+ ```
140
+
141
+ See [service limitations][data_limits] for the input, including document length limits, maximum batch size, and supported text encodings.
142
+
143
+ ### Return Value
144
+
145
+ The return value corresponding to a single document is either a successful result or an error object. Each `TextAnalysisClient` method returns a heterogeneous array of results and errors that correspond to the inputs by index. A text input and its result will have the same index in the input and result collections.
146
+
147
+ An **result**, such as `SentimentAnalysisResult`, is the result of a Language operation, containing a prediction or predictions about a single text input. An operation's result type also may optionally include information about the input document and how it was processed.
148
+
149
+ The **error** object, `TextAnalysisErrorResult`, indicates that the service encountered an error while processing the document and contains information about the error.
150
+
151
+ ### Document Error Handling
152
+
153
+ In the collection returned by an operation, errors are distinguished from successful responses by the presence of the `error` property, which contains the inner `TextAnalysisError` object if an error was encountered. For successful result objects, this property is _always_ `undefined`.
154
+
155
+ For example, to filter out all errors, you could use the following `filter`:
156
+
157
+ ```javascript
158
+ const results = await client.analyze("SentimentAnalysis", documents);
159
+ const onlySuccessful = results.filter((result) => result.error === undefined);
160
+ ```
161
+
162
+ **Note**: TypeScript users can benefit from better type-checking of result and error objects if `compilerOptions.strictNullChecks` is set to `true` in the `tsconfig.json` configuration. For example:
163
+
164
+ ```typescript
165
+ const [result] = await client.analyze("SentimentAnalysis", ["Hello world!"]);
166
+
167
+ if (result.error !== undefined) {
168
+ // In this if block, TypeScript will be sure that the type of `result` is
169
+ // `TextAnalysisError` if compilerOptions.strictNullChecks is enabled in
170
+ // the tsconfig.json
171
+
172
+ console.log(result.error);
173
+ }
174
+ ```
175
+
176
+ ## Examples
177
+
178
+ ### Sentiment Analysis
179
+
180
+ Analyze sentiment of text to determine if it is positive, negative, neutral, or mixed, including per-sentence sentiment analysis and confidence scores.
181
+
182
+ ```javascript
183
+ const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");
184
+
185
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
186
+
187
+ const documents = [
188
+ "I did not like the restaurant. The food was too spicy.",
189
+ "The restaurant was decorated beautifully. The atmosphere was unlike any other restaurant I've been to.",
190
+ "The food was yummy. :)",
191
+ ];
192
+
193
+ async function main() {
194
+ const results = await client.analyze("SentimentAnalysis", documents);
195
+
196
+ for (const result of results) {
197
+ if (result.error === undefined) {
198
+ console.log("Overall sentiment:", result.sentiment);
199
+ console.log("Scores:", result.confidenceScores);
200
+ } else {
201
+ console.error("Encountered an error:", result.error);
202
+ }
203
+ }
204
+ }
205
+
206
+ main();
207
+ ```
208
+
209
+ To get more granular information about the opinions related to aspects of a product/service, also known as Aspect-based Sentiment Analysis in Natural Language Processing (NLP), see a sample on sentiment analysis with opinion mining [here][analyze_sentiment_opinion_mining_sample].
210
+
211
+ ### Entity Recognition
212
+
213
+ Recognize and categorize entities in text as people, places, organizations, dates/times, quantities, currencies, etc.
214
+
215
+ The `language` parameter is optional. If it is not specified, the default English model will be used.
216
+
217
+ ```javascript
218
+ const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");
219
+
220
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
221
+
222
+ const documents = [
223
+ "Microsoft was founded by Bill Gates and Paul Allen.",
224
+ "Redmond is a city in King County, Washington, United States, located 15 miles east of Seattle.",
225
+ "Jeff bought three dozen eggs because there was a 50% discount.",
226
+ ];
227
+
228
+ async function main() {
229
+ const results = await client.analyze("EntityRecognition", documents, "en");
230
+
231
+ for (const result of results) {
232
+ if (result.error === undefined) {
233
+ console.log(" -- Recognized entities for input", result.id, "--");
234
+ for (const entity of result.entities) {
235
+ console.log(entity.text, ":", entity.category, "(Score:", entity.confidenceScore, ")");
236
+ }
237
+ } else {
238
+ console.error("Encountered an error:", result.error);
239
+ }
240
+ }
241
+ }
242
+
243
+ main();
244
+ ```
245
+
246
+ ### PII Entity Recognition
247
+
248
+ There is a separate action for recognizing Personally Identifiable Information (PII) in text such as Social Security Numbers, bank account information, credit card numbers, etc. Its usage is very similar to the standard entity recognition above:
249
+
250
+ ```javascript
251
+ const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");
252
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
253
+ const documents = [
254
+ "The employee's SSN is 555-55-5555.",
255
+ "The employee's phone number is (555) 555-5555.",
256
+ ];
257
+ async function main() {
258
+ const results = await client.analyze("PiiEntityRecognition", documents, "en");
259
+ for (const result of results) {
260
+ if (result.error === undefined) {
261
+ console.log(" -- Recognized PII entities for input", result.id, "--");
262
+ for (const entity of result.entities) {
263
+ console.log(entity.text, ":", entity.category, "(Score:", entity.confidenceScore, ")");
264
+ }
265
+ } else {
266
+ console.error("Encountered an error:", result.error);
267
+ }
268
+ }
269
+ }
270
+ main();
271
+ ```
272
+
273
+ ### Entity Linking
274
+
275
+ A "Linked" entity is one that exists in a knowledge base (such as Wikipedia). The `EntityLinking` action can disambiguate entities by determining which entry in a knowledge base they likely refer to (for example, in a piece of text, does the word "Mars" refer to the planet, or to the Roman god of war). Linked entities contain associated URLs to the knowledge base that provides the definition of the entity.
276
+
277
+ ```javascript
278
+ const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");
279
+
280
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
281
+
282
+ const documents = [
283
+ "Microsoft was founded by Bill Gates and Paul Allen.",
284
+ "Easter Island, a Chilean territory, is a remote volcanic island in Polynesia.",
285
+ "I use Azure Functions to develop my product.",
286
+ ];
287
+
288
+ async function main() {
289
+ const results = await client.analyze("EntityLinking", documents, "en");
290
+
291
+ for (const result of results) {
292
+ if (result.error === undefined) {
293
+ console.log(" -- Recognized linked entities for input", result.id, "--");
294
+ for (const entity of result.entities) {
295
+ console.log(entity.name, "(URL:", entity.url, ", Source:", entity.dataSource, ")");
296
+ for (const match of entity.matches) {
297
+ console.log(
298
+ " Occurrence:",
299
+ '"' + match.text + '"',
300
+ "(Score:",
301
+ match.confidenceScore,
302
+ ")"
303
+ );
304
+ }
305
+ }
306
+ } else {
307
+ console.error("Encountered an error:", result.error);
308
+ }
309
+ }
310
+ }
311
+
312
+ main();
313
+ ```
314
+
315
+ ### Key Phrase Extraction
316
+
317
+ Key Phrase extraction identifies the main talking points in a document. For example, given input text "The food was delicious and there were wonderful staff", the service returns "food" and "wonderful staff".
318
+
319
+ ```javascript
320
+ const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");
321
+
322
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
323
+
324
+ const documents = [
325
+ "Redmond is a city in King County, Washington, United States, located 15 miles east of Seattle.",
326
+ "I need to take my cat to the veterinarian.",
327
+ "I will travel to South America in the summer.",
328
+ ];
329
+
330
+ async function main() {
331
+ const results = await client.analyze("KeyPhraseExtraction", documents, "en");
332
+
333
+ for (const result of results) {
334
+ if (result.error === undefined) {
335
+ console.log(" -- Extracted key phrases for input", result.id, "--");
336
+ console.log(result.keyPhrases);
337
+ } else {
338
+ console.error("Encountered an error:", result.error);
339
+ }
340
+ }
341
+ }
342
+
343
+ main();
344
+ ```
345
+
346
+ ### Language Detection
347
+
348
+ Determine the language of a piece of text.
349
+
350
+ The `countryHint` parameter is optional, but can assist the service in providing correct output if the country of origin is known. If provided, it should be set to an ISO-3166 Alpha-2 two-letter country code (such as "us" for the United States or "jp" for Japan) or to the value `"none"`. If the parameter is not provided, then the default `"us"` (United States) model will be used. If you do not know the country of origin of the document, then the parameter `"none"` should be used, and the Language service will apply a model that is tuned for an unknown country of origin.
351
+
352
+ ```javascript
353
+ const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");
354
+
355
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
356
+
357
+ const documents = [
358
+ "This is written in English.",
359
+ "Il documento scritto in italiano.",
360
+ "Dies ist in deutscher Sprache verfasst.",
361
+ ];
362
+
363
+ async function main() {
364
+ const results = await client.analyze("LanguageDetection", documents, "none");
365
+
366
+ for (const result of results) {
367
+ if (result.error === undefined) {
368
+ const { primaryLanguage } = result;
369
+ console.log(
370
+ "Input #",
371
+ result.id,
372
+ "identified as",
373
+ primaryLanguage.name,
374
+ "( ISO6391:",
375
+ primaryLanguage.iso6391Name,
376
+ ", Score:",
377
+ primaryLanguage.confidenceScore,
378
+ ")"
379
+ );
380
+ } else {
381
+ console.error("Encountered an error:", result.error);
382
+ }
383
+ }
384
+ }
385
+
386
+ main();
387
+ ```
388
+
389
+ ### Healthcare Analysis
390
+
391
+ Healthcare analysis identifies healthcare entities. For example, given input text "Prescribed 100mg ibuprofen, taken twice daily", the service returns "100mg" categorized as Dosage, "ibuprofen" as MedicationName, and "twice daily" as Frequency.
392
+
393
+ ```javascript
394
+ const {
395
+ AzureKeyCredential,
396
+ TextAnalysisClient,
397
+ } = require("@azure/ai-language-text");
398
+
399
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
400
+
401
+ const documents = [
402
+ "Prescribed 100mg ibuprofen, taken twice daily.",
403
+ "Patient does not suffer from high blood pressure.",
404
+ ];
405
+
406
+ async function main() {
407
+ const actions = [
408
+ {
409
+ kind: "Healthcare",
410
+ },
411
+ ];
412
+ const poller = await client.beginAnalyzeBatch(actions, documents, "en");
413
+ const results = await poller.pollUntilDone();
414
+ for await (const actionResult of results) {
415
+ if (actionResult.kind !== "Healthcare") {
416
+ throw new Error(`Expected a healthcare results but got: ${actionResult.kind}`);
417
+ }
418
+ if (actionResult.error) {
419
+ const { code, message } = actionResult.error;
420
+ throw new Error(`Unexpected error (${code}): ${message}`);
421
+ }
422
+ for (const result of actionResult.results) {
423
+ console.log(`- Document ${result.id}`);
424
+ if (result.error) {
425
+ const { code, message } = result.error;
426
+ throw new Error(`Unexpected error (${code}): ${message}`);
427
+ }
428
+ console.log("\tRecognized Entities:");
429
+ for (const entity of result.entities) {
430
+ console.log(`\t- Entity "${entity.text}" of type ${entity.category}`);
431
+ if (entity.dataSources.length > 0) {
432
+ console.log("\t and it can be referenced in the following data sources:");
433
+ for (const ds of entity.dataSources) {
434
+ console.log(`\t\t- ${ds.name} with Entity ID: ${ds.entityId}`);
435
+ }
436
+ }
437
+ }
438
+ }
439
+ }
440
+ }
441
+
442
+ main();
443
+ ```
444
+
445
+ ### Extractive Summarization
446
+
447
+ Extractive summarization identifies sentences that summarize the article they belong to.
448
+
449
+ ```javascript
450
+ const {
451
+ AzureKeyCredential,
452
+ TextAnalysisClient,
453
+ } = require("@azure/ai-language-text");
454
+
455
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
456
+
457
+ const documents = [
458
+ "Prescribed 100mg ibuprofen, taken twice daily.",
459
+ "Patient does not suffer from high blood pressure.",
460
+ ];
461
+
462
+ async function main() {
463
+ const actions = [
464
+ {
465
+ kind: "ExtractiveSummarization",
466
+ maxSentenceCount: 2,
467
+ },
468
+ ];
469
+ const poller = await client.beginAnalyzeBatch(actions, documents, "en");
470
+ const results = await poller.pollUntilDone();
471
+
472
+ for await (const actionResult of results) {
473
+ if (actionResult.kind !== "ExtractiveSummarization") {
474
+ throw new Error(`Expected extractive summarization results but got: ${actionResult.kind}`);
475
+ }
476
+ if (actionResult.error) {
477
+ const { code, message } = actionResult.error;
478
+ throw new Error(`Unexpected error (${code}): ${message}`);
479
+ }
480
+ for (const result of actionResult.results) {
481
+ console.log(`- Document ${result.id}`);
482
+ if (result.error) {
483
+ const { code, message } = result.error;
484
+ throw new Error(`Unexpected error (${code}): ${message}`);
485
+ }
486
+ console.log("Summary:");
487
+ console.log(result.sentences.map((sentence) => sentence.text).join("\n"));
488
+ }
489
+ }
490
+ }
491
+
492
+ main();
493
+ ```
494
+
495
+ ### Custom Entity Recognition
496
+
497
+ Recognize and categorize entities in text as entities using custom entity detection models built using [Azure Language Studio][lang_studio].
498
+
499
+ ```javascript
500
+ const {
501
+ AzureKeyCredential,
502
+ TextAnalysisClient,
503
+ } = require("@azure/ai-language-text");
504
+
505
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
506
+
507
+ const documents = [
508
+ "We love this trail and make the trip every year. The views are breathtaking and well worth the hike! Yesterday was foggy though, so we missed the spectacular views. We tried again today and it was amazing. Everyone in my family liked the trail although it was too challenging for the less athletic among us.",
509
+ "Last week we stayed at Hotel Foo to celebrate our anniversary. The staff knew about our anniversary so they helped me organize a little surprise for my partner. The room was clean and with the decoration I requested. It was perfect!",
510
+ ];
511
+
512
+ async function main() {
513
+ const actions = [
514
+ {
515
+ kind: "CustomEntityRecognition",
516
+ deploymentName,
517
+ projectName,
518
+ },
519
+ ];
520
+ const poller = await client.beginAnalyzeBatch(actions, documents, "en");
521
+ for await (const actionResult of results) {
522
+ if (actionResult.kind !== "CustomEntityRecognition") {
523
+ throw new Error(`Expected a CustomEntityRecognition results but got: ${actionResult.kind}`);
524
+ }
525
+ if (actionResult.error) {
526
+ const { code, message } = actionResult.error;
527
+ throw new Error(`Unexpected error (${code}): ${message}`);
528
+ }
529
+ for (const result of actionResult.results) {
530
+ console.log(`- Document ${result.id}`);
531
+ if (result.error) {
532
+ const { code, message } = result.error;
533
+ throw new Error(`Unexpected error (${code}): ${message}`);
534
+ }
535
+ console.log("\tRecognized Entities:");
536
+ for (const entity of result.entities) {
537
+ console.log(`\t- Entity "${entity.text}" of type ${entity.category}`);
538
+ }
539
+ }
540
+ }
541
+ }
542
+
543
+ main();
544
+ ```
545
+
546
+ ### Custom Single-label Classification
547
+
548
+ Classify documents using custom single-label models built using [Azure Language Studio][lang_studio].
549
+
550
+ ```javascript
551
+ const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-language-text");
552
+
553
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
554
+
555
+ const documents = [
556
+ "The plot begins with a large group of characters where everyone thinks that the two main ones should be together but foolish things keep them apart. Misunderstandings, miscommunication, and confusion cause a series of humorous situations.",
557
+ ];
558
+
559
+ async function main() {
560
+ const actions = [
561
+ {
562
+ kind: "CustomSingleLabelClassification",
563
+ deploymentName,
564
+ projectName,
565
+ },
566
+ ];
567
+ const poller = await client.beginAnalyzeBatch(actions, documents, "en");
568
+ const results = await poller.pollUntilDone();
569
+
570
+ for await (const actionResult of results) {
571
+ if (actionResult.kind !== "CustomSingleLabelClassification") {
572
+ throw new Error(
573
+ `Expected a CustomSingleLabelClassification results but got: ${actionResult.kind}`
574
+ );
575
+ }
576
+ if (actionResult.error) {
577
+ const { code, message } = actionResult.error;
578
+ throw new Error(`Unexpected error (${code}): ${message}`);
579
+ }
580
+ for (const result of actionResult.results) {
581
+ console.log(`- Document ${result.id}`);
582
+ if (result.error) {
583
+ const { code, message } = result.error;
584
+ throw new Error(`Unexpected error (${code}): ${message}`);
585
+ }
586
+ console.log(`\tClassification: ${result.classification.category}`);
587
+ }
588
+ }
589
+ }
590
+
591
+ main();
592
+ ```
593
+
594
+ ### Custom Multi-label Classification
595
+
596
+ Classify documents using custom multi-label models built using [Azure Language Studio][lang_studio].
597
+
598
+ ```javascript
599
+ const {
600
+ AzureKeyCredential,
601
+ TextAnalysisClient,
602
+ } = require("@azure/ai-language-text");
603
+
604
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
605
+
606
+ const documents = [
607
+ "The plot begins with a large group of characters where everyone thinks that the two main ones should be together but foolish things keep them apart. Misunderstandings, miscommunication, and confusion cause a series of humorous situations.",
608
+ ];
609
+
610
+ async function main() {
611
+ const actions = [
612
+ {
613
+ kind: "CustomMultiLabelClassification",
614
+ deploymentName,
615
+ projectName,
616
+ },
617
+ ];
618
+ const poller = await client.beginAnalyzeBatch(actions, documents, "en");
619
+ const results = await poller.pollUntilDone();
620
+
621
+ for await (const actionResult of results) {
622
+ if (actionResult.kind !== "CustomMultiLabelClassification") {
623
+ throw new Error(
624
+ `Expected a CustomMultiLabelClassification results but got: ${actionResult.kind}`
625
+ );
626
+ }
627
+ if (actionResult.error) {
628
+ const { code, message } = actionResult.error;
629
+ throw new Error(`Unexpected error (${code}): ${message}`);
630
+ }
631
+ for (const result of actionResult.results) {
632
+ console.log(`- Document ${result.id}`);
633
+ if (result.error) {
634
+ const { code, message } = result.error;
635
+ throw new Error(`Unexpected error (${code}): ${message}`);
636
+ }
637
+ console.log(`\tClassification:`);
638
+ for (const classification of result.classifications) {
639
+ console.log(`\t\t-category: ${classification.category}`);
640
+ }
641
+ }
642
+ }
643
+ }
644
+
645
+ main();
646
+ ```
647
+
648
+ ### Action Batching
649
+
650
+ Applies multiple actions on each input document in one service request.
651
+
652
+ ```javascript
653
+ const {
654
+ AzureKeyCredential,
655
+ TextAnalysisClient,
656
+ } = require("@azure/ai-language-text");
657
+
658
+ const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
659
+
660
+ const documents = [
661
+ "Microsoft was founded by Bill Gates and Paul Allen.",
662
+ "The employee's SSN is 555-55-5555.",
663
+ "Easter Island, a Chilean territory, is a remote volcanic island in Polynesia.",
664
+ "I use Azure Functions to develop my product.",
665
+ ];
666
+
667
+ async function main() {
668
+ const actions = [
669
+ {
670
+ kind: "EntityRecognition",
671
+ modelVersion: "latest",
672
+ },
673
+ {
674
+ kind: "PiiEntityRecognition",
675
+ modelVersion: "latest",
676
+ },
677
+ {
678
+ kind: "KeyPhraseExtraction",
679
+ modelVersion: "latest",
680
+ },
681
+ ];
682
+ const poller = await client.beginAnalyzeBatch(actions, documents, "en");
683
+ const actionResults = await poller.pollUntilDone();
684
+ for await (const actionResult of actionResults) {
685
+ if (actionResult.error) {
686
+ const { code, message } = actionResult.error;
687
+ throw new Error(`Unexpected error (${code}): ${message}`);
688
+ }
689
+ switch (actionResult.kind) {
690
+ case "KeyPhraseExtraction": {
691
+ for (const doc of actionResult.results) {
692
+ console.log(`- Document ${doc.id}`);
693
+ if (!doc.error) {
694
+ console.log("\tKey phrases:");
695
+ for (const phrase of doc.keyPhrases) {
696
+ console.log(`\t- ${phrase}`);
697
+ }
698
+ } else {
699
+ console.error("\tError:", doc.error);
700
+ }
701
+ }
702
+ break;
703
+ }
704
+ case "EntityRecognition": {
705
+ for (const doc of actionResult.results) {
706
+ console.log(`- Document ${doc.id}`);
707
+ if (!doc.error) {
708
+ console.log("\tEntities:");
709
+ for (const entity of doc.entities) {
710
+ console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
711
+ }
712
+ } else {
713
+ console.error("\tError:", doc.error);
714
+ }
715
+ }
716
+ break;
717
+ }
718
+ case "PiiEntityRecognition": {
719
+ for (const doc of actionResult.results) {
720
+ console.log(`- Document ${doc.id}`);
721
+ if (!doc.error) {
722
+ console.log("\tPii Entities:");
723
+ for (const entity of doc.entities) {
724
+ console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
725
+ }
726
+ } else {
727
+ console.error("\tError:", doc.error);
728
+ }
729
+ }
730
+ break;
731
+ }
732
+ default: {
733
+ throw new Error(`Unexpected action results: ${actionResult.kind}`);
734
+ }
735
+ }
736
+ }
737
+ }
738
+
739
+ main();
740
+ ```
741
+
742
+ ## Troubleshooting
743
+
744
+ ### Logging
745
+
746
+ Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`:
747
+
748
+ ```javascript
749
+ const { setLogLevel } = require("@azure/logger");
750
+
751
+ setLogLevel("info");
752
+ ```
753
+
754
+ For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger).
755
+
756
+ ## Next steps
757
+
758
+ Please take a look at the [samples](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/cognitivelanguage/ai-language-text/samples-dev) directory for detailed examples on how to use this library.
759
+
760
+ ## Contributing
761
+
762
+ If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code.
763
+
764
+ ## Related projects
765
+
766
+ - [Microsoft Azure SDK for JavaScript](https://github.com/Azure/azure-sdk-for-js)
767
+
768
+ ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js%2Fsdk%2Fcognitivelanguage%2Fai-language-text%2FREADME.png)
769
+
770
+ [azure_cli]: https://docs.microsoft.com/cli/azure
771
+ [azure_sub]: https://azure.microsoft.com/free/
772
+ [cognitive_resource]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account
773
+ [azure_portal]: https://portal.azure.com
774
+ [azure_identity]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity
775
+ [cognitive_auth]: https://docs.microsoft.com/azure/cognitive-services/authentication
776
+ [register_aad_app]: https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal
777
+ [defaultazurecredential]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential
778
+ [data_limits]: https://docs.microsoft.com/azure/cognitive-services/language-service/concepts/data-limits
779
+ [analyze_sentiment_opinion_mining_sample]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/cognitivelanguage/ai-language-text/samples-dev/opinionMining.ts
780
+ [lang_studio]: https://docs.microsoft.com/azure/cognitive-services/language-service/language-studio