Skip to content

Commit 6ba1754

Browse files
committed
Content safety test quickstart - TS
1 parent d6dd847 commit 6ba1754

File tree

1 file changed

+182
-0
lines changed

1 file changed

+182
-0
lines changed
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
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/) for writing the sample code
21+
* [Visual Studio Code](https://code.visualstudio.com/) or another IDE of your choice
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+
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+
Initialize a new Node.js project with TypeScript:
35+
36+
```bash
37+
npm init -y
38+
npm pkg set type=module
39+
```
40+
41+
3. Install the required packages:
42+
43+
```bash
44+
npm install @azure-rest/ai-content-safety @azure/core-auth
45+
```
46+
47+
4. Install development dependencies:
48+
49+
```bash
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 `resources` folder and add a sample image to it.
94+
95+
8. Create a `src` directory for your TypeScript code.
96+
97+
[!INCLUDE [Create environment variables](../env-vars.md)]
98+
99+
## Analyze text content
100+
101+
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.
102+
103+
> [!TIP]
104+
> Text size and granularity
105+
>
106+
> See [Input requirements](../../overview.md#input-requirements) for maximum text length limitations.
107+
108+
```typescript
109+
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
110+
import { AzureKeyCredential } from "@azure/core-auth";
111+
112+
// Define interfaces for better type safety
113+
interface TextAnalysisOptions {
114+
text: string;
115+
}
116+
117+
interface CategoryAnalysis {
118+
category: string;
119+
severity: number;
120+
}
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+
// Create client with Azure Key Credential
132+
const credential = new AzureKeyCredential(key);
133+
const client = ContentSafetyClient(endpoint, credential);
134+
135+
// Replace with your own sample text string
136+
const text = "<your sample text>";
137+
const analyzeTextOption: TextAnalysisOptions = { text };
138+
const analyzeTextParameters = { body: analyzeTextOption };
139+
140+
// Call the Content Safety API to analyze the text
141+
const result = await client.path("/text:analyze").post(analyzeTextParameters);
142+
143+
if (isUnexpected(result)) {
144+
throw result;
145+
}
146+
147+
// Process and display the analysis results
148+
console.log("Text analysis results:");
149+
150+
const categoriesAnalysis = result.body.categoriesAnalysis as CategoryAnalysis[];
151+
152+
for (const analysis of categoriesAnalysis) {
153+
console.log(`${analysis.category} severity: ${analysis.severity}`);
154+
}
155+
} catch (error: any) {
156+
console.error("The sample encountered an error:", error.message);
157+
}
158+
```
159+
160+
## Build and run the application
161+
162+
1. Build the TypeScript code:
163+
164+
```bash
165+
npm run build
166+
```
167+
168+
2. Run the application:
169+
170+
```bash
171+
npm start
172+
```
173+
174+
## Output
175+
176+
```console
177+
Text analysis results:
178+
Hate severity: 0
179+
SelfHarm severity: 0
180+
Sexual severity: 0
181+
Violence severity: 0
182+
```

0 commit comments

Comments
 (0)