Skip to content

Commit 6382471

Browse files
authored
Merge pull request #5996 from diberry/diberry/pfarley-ts-content-safety-text
Content safety text quickstart - TS
2 parents 88706af + 0e6ee45 commit 6382471

File tree

5 files changed

+389
-5
lines changed

5 files changed

+389
-5
lines changed
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
---
2+
title: "Quickstart: Analyze image content with TypeScript"
3+
description: In this quickstart, get started using the Azure AI Content Safety TypeScript SDK to analyze image content for objectionable material.
4+
author: PatrickFarley
5+
manager: nitinme
6+
ms.service: azure-ai-content-safety
7+
ms.custom:
8+
ms.topic: include
9+
ms.date: 07/11/2025
10+
ms.author: pafarley
11+
---
12+
13+
[Reference documentation](https://www.npmjs.com/package/@azure-rest/ai-content-safety/v/1.0.0) | [Library source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/contentsafety/ai-content-safety-rest) | [Package (npm)](https://www.npmjs.com/package/@azure-rest/ai-content-safety) | [Samples](https://github.com/Azure-Samples/AzureAIContentSafety/tree/main/js/1.0.0) |
14+
15+
16+
## Prerequisites
17+
18+
* An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services/)
19+
* [Node.js LTS](https://nodejs.org/)
20+
* [TypeScript](https://www.typescriptlang.org/)
21+
* [Visual Studio Code](https://code.visualstudio.com/)
22+
* Once you have your Azure subscription, <a href="https://aka.ms/acs-create" title="Create a Content Safety resource" target="_blank">create a Content Safety resource </a> in the Azure portal to get your key and endpoint. Enter a unique name for your resource, select your subscription, and select a resource group, supported region (see [Region availability](/azure/ai-services/content-safety/overview#region-availability)), and supported pricing tier. Then select **Create**.
23+
* The resource takes a few minutes to deploy. After it finishes, Select **go to resource**. In the left pane, under **Resource Management**, select **Subscription Key and Endpoint**. The endpoint and either of the keys are used to call APIs.
24+
25+
## Set up local development environment
26+
27+
1. Create a new directory for your project and navigate to it:
28+
29+
```console
30+
mkdir content-safety-image-analysis
31+
cd content-safety-image-analysis
32+
code .
33+
```
34+
35+
2. Create a new package for ESM modules in your project directory:
36+
37+
```console
38+
npm init -y
39+
npm pkg set type=module
40+
```
41+
42+
3. Install the required packages:
43+
44+
```console
45+
npm install @azure-rest/ai-content-safety
46+
```
47+
48+
4. Install development dependencies:
49+
50+
```console
51+
npm install typescript @types/node --save-dev
52+
```
53+
54+
5. Create a `tsconfig.json` file in your project directory:
55+
56+
```json
57+
{
58+
"compilerOptions": {
59+
"target": "es2022",
60+
"module": "esnext",
61+
"moduleResolution": "bundler",
62+
"rootDir": "./src",
63+
"outDir": "./dist/",
64+
"esModuleInterop": true,
65+
"forceConsistentCasingInFileNames": true,
66+
"strict": true,
67+
"skipLibCheck": true,
68+
"declaration": true,
69+
"sourceMap": true,
70+
"resolveJsonModule": true,
71+
"moduleDetection": "force",
72+
"allowSyntheticDefaultImports": true,
73+
"verbatimModuleSyntax": false
74+
},
75+
"include": [
76+
"src/**/*.ts"
77+
],
78+
"exclude": [
79+
"node_modules/**/*",
80+
"**/*.spec.ts"
81+
]
82+
}
83+
```
84+
85+
6. Update `package.json` to include a script for building TypeScript files:
86+
87+
```json
88+
"scripts": {
89+
"build": "tsc",
90+
"start": "node dist/index.js"
91+
}
92+
```
93+
94+
7. Create a `resources` folder and add a sample image to it.
95+
96+
8. Create a `src` directory for your TypeScript code.
97+
98+
[!INCLUDE [Create environment variables](../env-vars.md)]
99+
100+
## Analyze image content
101+
102+
Create a new file in your `src` directory, `index.ts` and paste in the following code. Replace the string used to create the `imagePath` variable with the path to your sample image.
103+
104+
```typescript
105+
import ContentSafetyClient, {
106+
isUnexpected,
107+
AnalyzeImageParameters,
108+
AnalyzeImage200Response,
109+
AnalyzeImageDefaultResponse,
110+
AnalyzeImageOptions,
111+
ImageCategoriesAnalysisOutput
112+
} from "@azure-rest/ai-content-safety";
113+
import { AzureKeyCredential } from "@azure/core-auth";
114+
import * as fs from "fs";
115+
import * as path from "path";
116+
import { fileURLToPath } from "url";
117+
118+
// Create __dirname equivalent for ESM modules
119+
const __filename = fileURLToPath(import.meta.url);
120+
const __dirname = path.dirname(__filename);
121+
122+
// Get endpoint and key from environment variables
123+
const endpoint = process.env.CONTENT_SAFETY_ENDPOINT;
124+
const key = process.env.CONTENT_SAFETY_KEY;
125+
126+
if (!endpoint || !key) {
127+
throw new Error("Missing required environment variables CONTENT_SAFETY_ENDPOINT or CONTENT_SAFETY_KEY");
128+
}
129+
130+
try {
131+
132+
const credential = new AzureKeyCredential(key);
133+
const client = ContentSafetyClient(endpoint, credential);
134+
135+
const imagePath = path.join(__dirname, '../resources/image.jpg');
136+
137+
const imageBuffer = fs.readFileSync(imagePath);
138+
const base64Image = imageBuffer.toString("base64");
139+
const analyzeImageOption: AnalyzeImageOptions = { image: { content: base64Image } };
140+
const analyzeImageParameters: AnalyzeImageParameters = { body: analyzeImageOption };
141+
142+
const result: AnalyzeImage200Response | AnalyzeImageDefaultResponse = await client.path("/image:analyze").post(analyzeImageParameters);
143+
144+
if (isUnexpected(result)) {
145+
throw result;
146+
}
147+
148+
const categoriesAnalysis = result.body.categoriesAnalysis as ImageCategoriesAnalysisOutput[];
149+
150+
for (const analysis of categoriesAnalysis) {
151+
console.log(`${analysis.category} severity: ${analysis.severity}`);
152+
}
153+
} catch (error) {
154+
console.error("Error analyzing image:", error);
155+
}
156+
```
157+
158+
## Build and run the sample
159+
160+
1. Compile the TypeScript code:
161+
162+
```console
163+
npm run build
164+
```
165+
166+
1. Run the compiled JavaScript:
167+
168+
```console
169+
node dist/index.js
170+
```
171+
172+
## Output
173+
174+
```console
175+
Hate severity: 0
176+
SelfHarm severity: 0
177+
Sexual severity: 0
178+
Violence severity: 0
179+
```
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
---
2+
title: "Quickstart: Analyze text content with TypeScript"
3+
description: In this quickstart, get started using the Azure AI Content Safety TypeScript SDK to analyze text content for objectionable material.
4+
author: PatrickFarley
5+
manager: nitinme
6+
ms.service: azure-ai-content-safety
7+
ms.custom:
8+
ms.topic: include
9+
ms.date: 07/11/2025
10+
ms.author: pafarley
11+
---
12+
13+
[Reference documentation](https://www.npmjs.com/package/@azure-rest/ai-content-safety) | [Library source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/contentsafety/ai-content-safety-rest) | [Package (npm)](https://www.npmjs.com/package/@azure-rest/ai-content-safety) | [Samples](https://github.com/Azure-Samples/AzureAIContentSafety/tree/main/js/1.0.0) |
14+
15+
16+
## Prerequisites
17+
18+
* An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services/)
19+
* [Node.js LTS](https://nodejs.org/)
20+
* [TypeScript](https://www.typescriptlang.org/)
21+
* [Visual Studio Code](https://code.visualstudio.com/)
22+
* Once you have your Azure subscription, <a href="https://aka.ms/acs-create" title="Create a Content Safety resource" target="_blank">create a Content Safety resource </a> in the Azure portal to get your key and endpoint. Enter a unique name for your resource, select your subscription, and select a resource group, supported region (see [Region availability](/azure/ai-services/content-safety/overview#region-availability)), and supported pricing tier. Then select **Create**.
23+
* The resource takes a few minutes to deploy. After it finishes, Select **go to resource**. In the left pane, under **Resource Management**, select **Subscription Key and Endpoint**. The endpoint and either of the keys are used to call APIs.
24+
25+
## Set up application
26+
27+
1. Create a new TypeScript application. In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.
28+
29+
```console
30+
mkdir content-safety-typescript && cd content-safety-typescript
31+
code .
32+
```
33+
34+
2. Initialize a new Node.js project with TypeScript:
35+
36+
```console
37+
npm init -y
38+
npm pkg set type=module
39+
```
40+
41+
3. Install the required packages:
42+
43+
```console
44+
npm install @azure-rest/ai-content-safety @azure/core-auth
45+
```
46+
47+
4. Install development dependencies:
48+
49+
```console
50+
npm install typescript @types/node --save-dev
51+
```
52+
53+
5. Create a `tsconfig.json` file in your project directory:
54+
55+
```json
56+
{
57+
"compilerOptions": {
58+
"target": "es2022",
59+
"module": "esnext",
60+
"moduleResolution": "bundler",
61+
"rootDir": "./src",
62+
"outDir": "./dist/",
63+
"esModuleInterop": true,
64+
"forceConsistentCasingInFileNames": true,
65+
"strict": true,
66+
"skipLibCheck": true,
67+
"declaration": true,
68+
"sourceMap": true,
69+
"resolveJsonModule": true,
70+
"moduleDetection": "force",
71+
"allowSyntheticDefaultImports": true,
72+
"verbatimModuleSyntax": false
73+
},
74+
"include": [
75+
"src/**/*.ts"
76+
],
77+
"exclude": [
78+
"node_modules/**/*",
79+
"**/*.spec.ts"
80+
]
81+
}
82+
```
83+
84+
6. Update `package.json` to include a script for building TypeScript files:
85+
86+
```json
87+
"scripts": {
88+
"build": "tsc",
89+
"start": "node dist/index.js"
90+
}
91+
```
92+
93+
7. Create a `src` directory for your TypeScript code.
94+
95+
[!INCLUDE [Create environment variables](../env-vars.md)]
96+
97+
## Analyze text content
98+
99+
Create a file in the `src` directory named `index.ts`. Open it in your preferred editor or IDE and paste in the following code. Replace `<your text sample>` with the text content you'd like to analyze.
100+
101+
> [!TIP]
102+
> Text size and granularity
103+
>
104+
> See [Input requirements](../../overview.md#input-requirements) for maximum text length limitations.
105+
106+
```typescript
107+
import ContentSafetyClient, {
108+
isUnexpected,
109+
AnalyzeTextParameters,
110+
AnalyzeText200Response,
111+
AnalyzeTextDefaultResponse,
112+
AnalyzeTextOptions,
113+
TextCategoriesAnalysisOutput
114+
} from "@azure-rest/ai-content-safety";
115+
import { AzureKeyCredential } from "@azure/core-auth";
116+
117+
// Get endpoint and key from environment variables
118+
const endpoint = process.env.CONTENT_SAFETY_ENDPOINT;
119+
const key = process.env.CONTENT_SAFETY_KEY;
120+
121+
if (!endpoint || !key) {
122+
throw new Error("Missing required environment variables: CONTENT_SAFETY_ENDPOINT or CONTENT_SAFETY_KEY");
123+
}
124+
125+
try {
126+
// Create client with Azure Key Credential
127+
const credential = new AzureKeyCredential(key);
128+
const client = ContentSafetyClient(endpoint, credential);
129+
130+
// Replace with your own sample text string
131+
const text = "Replace with your text sample";
132+
const analyzeTextOption: AnalyzeTextOptions = { text };
133+
const analyzeTextParameters: AnalyzeTextParameters = { body: analyzeTextOption };
134+
135+
// Call the Content Safety API to analyze the text
136+
const result: AnalyzeText200Response | AnalyzeTextDefaultResponse = await client.path("/text:analyze").post(analyzeTextParameters);
137+
138+
if (isUnexpected(result)) {
139+
throw result;
140+
}
141+
142+
// Process and display the analysis results
143+
console.log("Text analysis results:");
144+
145+
const categoriesAnalysis = result.body.categoriesAnalysis as TextCategoriesAnalysisOutput[];
146+
147+
for (const analysis of categoriesAnalysis) {
148+
console.log(`${analysis.category} severity: ${analysis.severity}`);
149+
}
150+
} catch (error: any) {
151+
console.error("The sample encountered an error:", error.message);
152+
}
153+
```
154+
155+
## Build and run the application
156+
157+
1. Build the TypeScript code:
158+
159+
```console
160+
npm run build
161+
```
162+
163+
2. Run the application:
164+
165+
```console
166+
npm start
167+
```
168+
169+
## Output
170+
171+
```console
172+
Text analysis results:
173+
Hate severity: 0
174+
SelfHarm severity: 0
175+
Sexual severity: 0
176+
Violence severity: 0
177+
```

articles/ai-services/content-safety/quickstart-image.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ manager: nitinme
77
ms.service: azure-ai-content-safety
88
ms.custom: build-2023, devx-track-python, devx-track-dotnet, devx-track-extended-java, devx-track-js
99
ms.topic: quickstart
10-
ms.date: 01/22/2025
10+
ms.date: 07/14/2025
1111
ms.author: pafarley
12-
zone_pivot_groups: programming-languages-content-safety
12+
zone_pivot_groups: programming-languages-content-safety-2
1313
---
1414

1515
# QuickStart: Analyze image content
@@ -58,7 +58,11 @@ For more information on image moderation, see the [Harm categories concept page]
5858

5959
::: zone-end
6060

61+
::: zone pivot="programming-language-typescript"
6162

63+
[!INCLUDE [TypeScript SDK quickstart](./includes/quickstarts/typescript-quickstart-image.md)]
64+
65+
::: zone-end
6266

6367
## Clean up resources
6468

0 commit comments

Comments
 (0)