Quickstart: Create a Cognitive Services resource using the Azure Management client library

Use this quickstart to create and manage Azure Cognitive Services resources using the Azure Management client library.

Azure Cognitive Services are cloud-based artificial intelligence (AI) services that help developers build cognitive intelligence into applications without having direct AI or data science skills or knowledge. They are available through REST APIs and client library SDKs in popular development languages. Azure Cognitive Services enables developers to easily add cognitive features into their applications with cognitive solutions that can see, hear, speak, and analyze.

Individual AI services are represented by Azure resources that you create under your Azure subscription. After you create a resource, you can use the keys and endpoint generated to authenticate your applications.

Reference documentation | Library source code | Package (NuGet) | Samples

C# prerequisites

  • A valid Azure subscription - Create one for free.
  • The current version of .NET Core.
  • Your Azure account must have a Cognitive Services Contributor role assigned in order for you to agree to the responsible AI terms and create a resource. To get this role assigned to your account, follow the steps in the Assign roles documentation, or contact your administrator.
  • You must create your first Face, Language service, or Computer Vision resources from the Azure portal to review and acknowledge the terms and conditions. You can do so here: Face, Language service, Computer Vision. After that, you can create subsequent resources using any deployment tool (SDK, CLI, or ARM template, etc) under the same Azure subscription.

Create an Azure Service Principal

To have your application interact with your Azure account, you need an Azure service principal to manage permissions. Follow the instructions in Create an Azure service principal.

When you create a service principal, you'll see it has a secret value, an ID, and an application ID. Save the application ID and secret to a temporary location for later steps.

Create a resource group

Before you create a Cognitive Services resource, your account must have an Azure resource group to contain the resource. If you don't already have a resource group, create one in the Azure portal before continuing.

Create a new C# application

Create a new .NET Core application. In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name azure-management-quickstart. This command creates a simple "Hello World" C# project with a single source file: program.cs.

dotnet new console -n azure-management-quickstart

Change your directory to the newly created app folder. You can build the application with:

dotnet build

The build output should contain no warnings or errors.

...
Build succeeded.
 0 Warning(s)
 0 Error(s)
...

Install the client library

Within the application directory, install the Azure Management client library for .NET with the following command:

dotnet add package Microsoft.Azure.Management.CognitiveServices
dotnet add package Microsoft.Azure.Management.Fluent
dotnet add package Microsoft.Azure.Management.ResourceManager.Fluent

If you're using the Visual Studio IDE, the client library is available as a downloadable NuGet package.

Import libraries

Open program.cs and add the following using statements to the top of the file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.CognitiveServices;
using Microsoft.Azure.Management.CognitiveServices.Models;

Authenticate the client

Add the following fields to the root of program.cs and populate their values, using the service principal you created and your Azure account information.

const string  service_principal_application_id = "PASTE_YOUR_SERVICE_PRINCIPAL_APPLICATION_ID_HERE";
const string  service_principal_secret = "PASTE_YOUR_SERVICE_PRINCIPAL_SECRET_HERE";

/* The ID of your Azure subscription. You can find this in the Azure Dashboard under Home > Subscriptions. */
const string  subscription_id = "PASTE_YOUR_SUBSCRIPTION_ID_HERE";

/* The Active Directory tenant ID. You can find this in the Azure Dashboard under Home > Azure Active Directory. */
const string  tenant_id = "PASTE_YOUR_TENANT_ID_HERE";

/* The name of the Azure resource group in which you want to create the resource.
You can find resource groups in the Azure Dashboard under Home > Resource groups. */
const string  resource_group_name = "PASTE_YOUR_RESOURCE_GROUP_NAME_HERE";

/* The name of the custom subdomain to use when you create the resource. This is optional.
For example, if you create a Bing Search v7 resource with the custom subdomain name 'my-search-resource',
your resource would have the endpoint https://my-search-resource.cognitiveservices.azure.com/.
Note not all Cognitive Services allow custom subdomain names. */
const string subdomain_name = "PASTE_YOUR_SUBDOMAIN_NAME_HERE";

Then, in your Main method, use these values to construct a CognitiveServicesManagementClient object. This object is needed for all of your Azure management operations.

var service_principal_credentials = new ServicePrincipalLoginInformation ();
service_principal_credentials.ClientId = service_principal_application_id;
service_principal_credentials.ClientSecret = service_principal_secret;

var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(service_principal_application_id, service_principal_secret, tenant_id, AzureEnvironment.AzureGlobalCloud);
var client = new CognitiveServicesManagementClient(credentials);
client.SubscriptionId = subscription_id;

Call management methods

Add the following code to your Main method to list available resources, create a sample resource, list your owned resources, and then delete the sample resource. You'll define these methods in the next steps.

    // Uncomment to list all available resource kinds, SKUs, and locations for your Azure account:
    //list_available_kinds_skus_locations(client);

    // Create a resource with kind TextTranslation, F0 (free tier), location global.
    create_resource(client, "test_resource", "TextTranslation", "F0", "Global");

    // List all resources for your Azure account and resource group:
    list_resources(client);

    // Delete the resource.
    delete_resource(client, "test_resource");

    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();

Create a Cognitive Services resource (C#)

To create and subscribe to a new Cognitive Services resource, use the Create method. This method adds a new billable resource to the resource group you pass in. When creating your new resource, you'll need to know the "kind" of service you want to use, along with its pricing tier (or SKU) and an Azure location. The following method takes all of these as arguments and creates a resource.

static void create_resource(CognitiveServicesManagementClient client, string resource_name, string kind, string account_tier, string location)
{
    Console.WriteLine("Creating resource: " + resource_name + "...");
    /* NOTE If you do not want to use a custom subdomain name, remove the customSubDomainName
    property from CognitiveServicesAccountProperties. */
    CognitiveServicesAccount parameters = 
        new CognitiveServicesAccount(null, null, kind, location, resource_name, new CognitiveServicesAccountProperties(customSubDomainName : subdomain_name), new Sku(account_tier));
    var result = client.Accounts.Create(resource_group_name, resource_name, parameters);
    Console.WriteLine("Resource created.");
    Console.WriteLine("ID: " + result.Id);
    Console.WriteLine("Kind: " + result.Kind);
    Console.WriteLine();
}

Choose a service and pricing tier

When you create a new resource, you'll need to know the "kind" of service you want to use, along with the pricing tier (or SKU) you want. You'll use this and other information as parameters when creating the resource. You can find a list of available Cognitive Service "kinds" by calling the following method in your script:

static void list_available_kinds_skus_locations(CognitiveServicesManagementClient client)
{

    Console.WriteLine("Available SKUs:");
    var result = client.ResourceSkus.List();
    Console.WriteLine("Kind\tSKU Name\tSKU Tier\tLocations");
    foreach (var x in result) {
        var locations = "";
        foreach (var region in x.Locations)
        {
            locations += region;
        }
        Console.WriteLine(x.Kind + "\t" + x.Name + "\t" + x.Tier + "\t" + locations);
    };
}

You can access Azure Cognitive Services through two different resources: A multi-service resource, or a single-service one.

  • Multi-service resource:
    • Access multiple Azure Cognitive Services with a single key and endpoint.
    • Consolidates billing from the services you use.
  • Single-service resource:
    • Access a single Azure Cognitive Service with a unique key and endpoint for each service created.
    • Use the free tier to try out the service.

See the list of SKUs and pricing information below.

Multi-service

Service Kind
Multiple services. For more information, see the pricing page. CognitiveServices

Vision

Service Kind
Computer Vision ComputerVision
Custom Vision - Prediction CustomVision.Prediction
Custom Vision - Training CustomVision.Training
Face Face
Form Recognizer FormRecognizer

Speech

Service Kind
Speech Services SpeechServices

Language

Service Kind
LUIS LUIS
QnA Maker QnAMaker
Language service TextAnalytics
Text Translation TextTranslation

Decision

Service Kind
Anomaly Detector AnomalyDetector
Content Moderator ContentModerator
Personalizer Personalizer

Pricing tiers and billing

Pricing tiers (and the amount you get billed) are based on the number of transactions you send using your authentication information. Each pricing tier specifies the:

  • maximum number of allowed transactions per second (TPS).
  • service features enabled within the pricing tier.
  • cost for a predefined number of transactions. Going above this number will cause an extra charge as specified in the pricing details for your service.

Note

Many of the Cognitive Services have a free tier you can use to try the service. To use the free tier, use F0 as the SKU for your resource.

View your resources

To view all of the resources under your Azure account (across all resource groups), use the following method:

static void list_resources(CognitiveServicesManagementClient client)
{
    Console.WriteLine("Resources in resource group: " + resource_group_name);
    var result = client.Accounts.ListByResourceGroup(resource_group_name);
    foreach (var x in result)
    {
        Console.WriteLine("ID: " + x.Id);
        Console.WriteLine("Name: " + x.Name);
        Console.WriteLine("Type: " + x.Type);
        Console.WriteLine("Kind: " + x.Kind);
        Console.WriteLine();
    }
}

Delete a resource

The following method deletes the specified resource from the given resource group.

static void delete_resource(CognitiveServicesManagementClient client, string resource_name)
{
    Console.WriteLine("Deleting resource: " + resource_name + "...");
    client.Accounts.Delete (resource_group_name, resource_name);

    Console.WriteLine("Resource deleted.");
    Console.WriteLine();
}

If you need to recover a deleted resource, see Recover deleted Cognitive Services resources.

Run the application

Run the application from your application directory with the dotnet run command.

dotnet run

See also

Reference documentation | Library source code | Package (Maven)

Java prerequisites

  • A valid Azure subscription - Create one for free.
  • The current version of the Java Development Kit(JDK)
  • The Gradle build tool, or another dependency manager.
  • Your Azure account must have a Cognitive Services Contributor role assigned in order for you to agree to the responsible AI terms and create a resource. To get this role assigned to your account, follow the steps in the Assign roles documentation, or contact your administrator.
  • You must create your first Face, Language service, or Computer Vision resources from the Azure portal to review and acknowledge the terms and conditions. You can do so here: Face, Language service, Computer Vision. After that, you can create subsequent resources using any deployment tool (SDK, CLI, or ARM template, etc) under the same Azure subscription.

Create an Azure Service Principal

To have your application interact with your Azure account, you need an Azure service principal to manage permissions. Follow the instructions in Create an Azure service principal.

When you create a service principal, you'll see it has a secret value, an ID, and an application ID. Save the application ID and secret to a temporary location for later steps.

Create a resource group

Before you create a Cognitive Services resource, your account must have an Azure resource group to contain the resource. If you don't already have a resource group, create one in the Azure portal before continuing.

Create a new Java application

In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.

mkdir myapp && cd myapp

Run the gradle init command from your working directory. This command will create essential build files for Gradle, including build.gradle.kts which is used at runtime to create and configure your application.

gradle init --type basic

When prompted to choose a DSL, select Kotlin.

From your working directory, run the following command:

mkdir -p src/main/java

Install the client library

This quickstart uses the Gradle dependency manager. You can find the client library and information for other dependency managers on the Maven Central Repository.

In your project's build.gradle.kts file, include the client library as an implementation statement, along with the required plugins and settings.

plugins {
    java
    application
}
application {
    mainClass.set("FormRecognizer")
}
repositories {
    mavenCentral()
}
dependencies {
    implementation(group = "com.microsoft.azure", name = "azure-mgmt-cognitiveservices", version = "1.10.0-beta")
}

Import libraries

Navigate to the new src/main/java folder and create a file called Management.java. Open it in your preferred editor or IDE and add the following import statements:

import com.azure.core.management.*;
import com.azure.core.management.profile.*;
import com.azure.identity.*;
import com.azure.resourcemanager.cognitiveservices.*;
import com.azure.resourcemanager.cognitiveservices.implementation.*;
import com.azure.resourcemanager.cognitiveservices.models.*;

import java.io.*;
import java.lang.Object.*;
import java.util.*;
import java.net.*;

Authenticate the client

Add a class in Management.java, and then add the following fields and their values inside of it. Populate their values, using the service principal you created and your other Azure account information.

/*
Be sure to use the service pricipal application ID, not simply the ID. 
*/

private static String applicationId = "PASTE_YOUR_SERVICE_PRINCIPAL_APPLICATION_ID_HERE";
private static String applicationSecret = "PASTE_YOUR_SERVICE_PRINCIPAL_SECRET_HERE";

/* The ID of your Azure subscription. You can find this in the Azure Dashboard under Home > Subscriptions. */
private static String subscriptionId = "PASTE_YOUR_SUBSCRIPTION_ID_HERE";

/* The Active Directory tenant ID. You can find this in the Azure Dashboard under Home > Azure Active Directory. */
private static String tenantId = "PASTE_YOUR_TENANT_ID_HERE";

/* The name of the Azure resource group in which you want to create the resource.
You can find resource groups in the Azure Dashboard under Home > Resource groups. */
private static String resourceGroupName = "PASTE_YOUR_RESOURCE_GROUP_NAME_HERE";

/* The name of the custom subdomain to use when you create the resource. This is optional.
For example, if you create a Bing Search v7 resource with the custom subdomain name 'my-search-resource',
your resource would have the endpoint https://my-search-resource.cognitiveservices.azure.com/.
Note not all Cognitive Services allow custom subdomain names. */
private static String subDomainName = "PASTE_YOUR_SUBDOMAIN_NAME_HERE";

Then, in your main method, use these values to construct a CognitiveServicesManager object. This object is needed for all of your Azure management operations.

/* For more information see:
https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/resourcemanager/docs/AUTH.md
*/

ClientSecretCredential credential = new ClientSecretCredentialBuilder()
    .clientId(applicationId)
    .clientSecret(applicationSecret)
    .tenantId(tenantId)
    .build();
AzureProfile profile = new AzureProfile(tenantId, subscriptionId, AzureEnvironment.AZURE);

CognitiveServicesManager client = CognitiveServicesManager.authenticate(credential, profile);

Call management methods

Add the following code to your Main method to list available resources, create a sample resource, list your owned resources, and then delete the sample resource. You'll define these methods in the next steps.

String resourceName = "test_resource";
String resourceKind = "TextTranslation";
String resourceSku = "F0";
Region resourceRegion = Region.US_WEST;

// Uncomment to list all available resource kinds, SKUs, and locations for your Azure account.
// list_available_kinds_skus_locations (client);

// Create a resource with kind Text Translation, SKU F0 (free tier), location US West.
String resourceId = create_resource (client, resourceName, resourceGroupName, resourceKind, resourceSku, resourceRegion);

// Uncomment this to list all resources for your Azure account.
// list_resources (client, resourceGroupName);

// Delete the resource.
delete_resource (client, resourceId);

/* NOTE: When you delete a resource, it is only soft-deleted. You must also purge it. Otherwise, if you try to create another
resource with the same name or custom subdomain, you will receive an error stating that such a resource already exists. */
purge_resource (client, resourceName, resourceGroupName, resourceRegion);

Create a Cognitive Services resource (Java)

To create and subscribe to a new Cognitive Services resource, use the create method. This method adds a new billable resource to the resource group you pass in. When creating your new resource, you'll need to know the "kind" of service you want to use, along with its pricing tier (or SKU) and an Azure location. The following method takes all of these as arguments and creates a resource.

public static String create_resource (CognitiveServicesManager client, String resourceName, String resourceGroupName, String resourceKind, String resourceSku, Region resourceRegion) {
    System.out.println ("Creating resource: " + resourceName + "...");

    /* NOTE: If you do not want to use a custom subdomain name, remove the withCustomSubDomainName
    setter from the AccountProperties object. */
    Account result = client.accounts().define(resourceName)
        .withExistingResourceGroup(resourceGroupName)
        // Note: Do not call withRegion() first, as it does not exist on the Blank interface returned by define().
        .withRegion(resourceRegion)
        .withKind(resourceKind)
        .withSku(new Sku().withName(resourceSku))
        .withProperties(new AccountProperties().withCustomSubDomainName(subDomainName))
        .create();

    System.out.println ("Resource created.");
    System.out.println ("ID: " + result.id());
    System.out.println ("Provisioning state: " + result.properties().provisioningState().toString());
    System.out.println ();

    return result.id();
}

Choose a service and pricing tier

When you create a new resource, you'll need to know the "kind" of service you want to use, along with the pricing tier (or SKU) you want. You'll use this and other information as parameters when creating the resource. You can find a list of available Cognitive Service "kinds" by calling the following method:

public static void list_available_kinds_skus_locations (CognitiveServicesManager client) {
    System.out.println ("Available SKUs:");
    System.out.println("Kind\tSKU Name\tSKU Tier\tLocations");
    ResourceSkus skus = client.resourceSkus();
    for (ResourceSku sku : skus.list()) {
        String locations = String.join (",", sku.locations());
        System.out.println (sku.kind() + "\t" + sku.name() + "\t" + sku.tier() + "\t" + locations);
    }
}

You can access Azure Cognitive Services through two different resources: A multi-service resource, or a single-service one.

  • Multi-service resource:
    • Access multiple Azure Cognitive Services with a single key and endpoint.
    • Consolidates billing from the services you use.
  • Single-service resource:
    • Access a single Azure Cognitive Service with a unique key and endpoint for each service created.
    • Use the free tier to try out the service.

See the list of SKUs and pricing information below.

Multi-service

Service Kind
Multiple services. For more information, see the pricing page. CognitiveServices

Vision

Service Kind
Computer Vision ComputerVision
Custom Vision - Prediction CustomVision.Prediction
Custom Vision - Training CustomVision.Training
Face Face
Form Recognizer FormRecognizer

Speech

Service Kind
Speech Services SpeechServices

Language

Service Kind
LUIS LUIS
QnA Maker QnAMaker
Language service TextAnalytics
Text Translation TextTranslation

Decision

Service Kind
Anomaly Detector AnomalyDetector
Content Moderator ContentModerator
Personalizer Personalizer

Pricing tiers and billing

Pricing tiers (and the amount you get billed) are based on the number of transactions you send using your authentication information. Each pricing tier specifies the:

  • maximum number of allowed transactions per second (TPS).
  • service features enabled within the pricing tier.
  • cost for a predefined number of transactions. Going above this number will cause an extra charge as specified in the pricing details for your service.

Note

Many of the Cognitive Services have a free tier you can use to try the service. To use the free tier, use F0 as the SKU for your resource.

View your resources

To view all of the resources under your Azure account (across all resource groups), use the following method:

public static void list_resources (CognitiveServicesManager client, String resourceGroupName) {
    System.out.println ("Resources in resource group: " + resourceGroupName);
    // Note Azure resources are also sometimes referred to as accounts.
    Accounts accounts = client.accounts();
    for (Account account : accounts.listByResourceGroup(resourceGroupName)) {
        System.out.println ("ID: " + account.id());
        System.out.println ("Kind: " + account.kind ());
        System.out.println ("SKU Name: " + account.sku().name());
        System.out.println ("Custom subdomain name: " + account.properties().customSubDomainName());
        System.out.println ();
    }
}

Delete a resource

The following method deletes the specified resource from the given resource group.

public static void delete_resource (CognitiveServicesManager client, String resourceId) {
    System.out.println ("Deleting resource: " + resourceId + "...");
    client.accounts().deleteById (resourceId);
    System.out.println ("Resource deleted.");
    System.out.println ();
}

If you need to recover a deleted resource, see Recover deleted Cognitive Services resources.

See also

Reference documentation | Library source code | Package (NPM) | Samples

JavaScript prerequisites

  • A valid Azure subscription - Create one for free.
  • The current version of Node.js
  • Your Azure account must have a Cognitive Services Contributor role assigned in order for you to agree to the responsible AI terms and create a resource. To get this role assigned to your account, follow the steps in the Assign roles documentation, or contact your administrator.
  • You must create your first Face, Language service, or Computer Vision resources from the Azure portal to review and acknowledge the terms and conditions. You can do so here: Face, Language service, Computer Vision. After that, you can create subsequent resources using any deployment tool (SDK, CLI, or ARM template, etc) under the same Azure subscription.

Create an Azure Service Principal

To have your application interact with your Azure account, you need an Azure service principal to manage permissions. Follow the instructions in Create an Azure service principal.

When you create a service principal, you'll see it has a secret value, an ID, and an application ID. Save the application ID and secret to a temporary location for later steps.

Create a resource group

Before you create a Cognitive Services resource, your account must have an Azure resource group to contain the resource. If you don't already have a resource group, create one in the Azure portal before continuing.

Create a new Node.js application

In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.

mkdir myapp && cd myapp

Run the npm init command to create a node application with a package.json file.

npm init

Create a file named index.js before going on.

Install the client library

Install the following NPM packages:

npm install @azure/arm-cognitiveservices
npm install @azure/identity

Your app's package.json file will be updated with the dependencies.

Import libraries

Open your index.js script and import the following libraries.

"use strict";

/* To run this sample, install the following modules.
 * npm install @azure/arm-cognitiveservices @azure/identity
 */
var Arm = require("@azure/arm-cognitiveservices");
var Identity = require("@azure/identity");

Authenticate the client

Add the following fields to the root of your script and fill in their values, using the service principal you created and your Azure account information.

const service_principal_application_id =
  "PASTE_YOUR_SERVICE_PRINCIPAL_APPLICATION_ID_HERE";
const service_principal_secret = "PASTE_YOUR_SERVICE_PRINCIPAL_SECRET_HERE";

/* The ID of your Azure subscription. You can find this in the Azure Dashboard under Home > Subscriptions. */
const subscription_id = "PASTE_YOUR_SUBSCRIPTION_ID_HERE";

/* The Active Directory tenant ID. You can find this in the Azure Dashboard under Home > Azure Active Directory. */
const tenant_id = "PASTE_YOUR_TENANT_ID_HERE";

/* The name of the Azure resource group in which you want to create the resource.
You can find resource groups in the Azure Dashboard under Home > Resource groups. */
const resource_group_name = "PASTE_YOUR_RESOURCE_GROUP_NAME_HERE";

/* The name of the custom subdomain to use when you create the resource. This is optional.
For example, if you create a Bing Search v7 resource with the custom subdomain name 'my-search-resource',
your resource would have the endpoint https://my-search-resource.cognitiveservices.azure.com/.
Note not all Cognitive Services allow custom subdomain names.
*/
const subdomain_name = "PASTE_YOUR_SUBDOMAIN_NAME_HERE";

Next, add the following quickstart function to handle the main work of your program. The first block of code constructs a CognitiveServicesManagementClient object using the credential variables you entered above. This object is needed for all of your Azure management operations.

async function quickstart() {
  /* For more information see:
https://www.npmjs.com/package/@azure/arm-cognitiveservices/v/6.0.0
https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-a-service-principal-with-a-client-secret
*/
  const credentials = new Identity.ClientSecretCredential(
    tenant_id,
    service_principal_application_id,
    service_principal_secret
  );
  const client = new Arm.CognitiveServicesManagementClient(
    credentials,
    subscription_id
  );
  // Note Azure resources are also sometimes referred to as accounts.
  const accounts_client = client.accounts;
  const resource_skus_client = client.resourceSkus;
  const deleted_accounts_client = client.deletedAccounts;

Call management functions

Add the following code to the end of your quickstart function to list available resources, create a sample resource, list your owned resources, and then delete the sample resource. You'll define these functions in the next steps.

Create a Cognitive Services resource (Node.js)

To create and subscribe to a new Cognitive Services resource, use the Create function. This function adds a new billable resource to the resource group you pass in. When you create your new resource, you'll need to know the "kind" of service you want to use, along with its pricing tier (or SKU) and an Azure location. The following function takes all of these arguments and creates a resource.

async function create_resource(
  client,
  resource_name,
  resource_kind,
  resource_sku,
  resource_region
) {
  console.log("Creating resource: " + resource_name + "...");
  /* NOTE If you do not want to use a custom subdomain name, remove the customSubDomainName
property from the properties object. */
  var parameters = {
    sku: { name: resource_sku },
    kind: resource_kind,
    location: resource_region,
    properties: { customSubDomainName: subdomain_name },
  };
  return client
    .beginCreateAndWait(resource_group_name, resource_name, parameters)
    .then((result) => {
      console.log("Resource created.");
      console.log();
      console.log("ID: " + result.id);
      console.log("Kind: " + result.kind);
      console.log();
    })
    .catch((err) => {
      console.log(err);
    });
}

Choose a service and pricing tier

When you create a new resource, you'll need to know the "kind" of service you want to use, along with the pricing tier (or SKU) you want. You'll use this and other information as parameters when creating the resource. The following function lists the available Cognitive Service "kinds."

async function list_available_kinds_skus_locations(client) {
  console.log("Available SKUs:");
  var result = client.list();
  console.log("Kind\tSKU Name\tSKU Tier\tLocations");
  for await (let item of result) {
    var locations = item.locations.join(",");
    console.log(item.kind + "\t" + item.name + "\t" + item.tier + "\t" + locations);
  }
}

You can access Azure Cognitive Services through two different resources: A multi-service resource, or a single-service one.

  • Multi-service resource:
    • Access multiple Azure Cognitive Services with a single key and endpoint.
    • Consolidates billing from the services you use.
  • Single-service resource:
    • Access a single Azure Cognitive Service with a unique key and endpoint for each service created.
    • Use the free tier to try out the service.

See the list of SKUs and pricing information below.

Multi-service

Service Kind
Multiple services. For more information, see the pricing page. CognitiveServices

Vision

Service Kind
Computer Vision ComputerVision
Custom Vision - Prediction CustomVision.Prediction
Custom Vision - Training CustomVision.Training
Face Face
Form Recognizer FormRecognizer

Speech

Service Kind
Speech Services SpeechServices

Language

Service Kind
LUIS LUIS
QnA Maker QnAMaker
Language service TextAnalytics
Text Translation TextTranslation

Decision

Service Kind
Anomaly Detector AnomalyDetector
Content Moderator ContentModerator
Personalizer Personalizer

Pricing tiers and billing

Pricing tiers (and the amount you get billed) are based on the number of transactions you send using your authentication information. Each pricing tier specifies the:

  • maximum number of allowed transactions per second (TPS).
  • service features enabled within the pricing tier.
  • cost for a predefined number of transactions. Going above this number will cause an extra charge as specified in the pricing details for your service.

Note

Many of the Cognitive Services have a free tier you can use to try the service. To use the free tier, use F0 as the SKU for your resource.

View your resources

To view all of the resources under your Azure account (across all resource groups), use the following function:

async function list_resources(client) {
  console.log("Resources in resource group: " + resource_group_name);
  var result = client.listByResourceGroup(resource_group_name);
  for await (let item of result) {
    console.log(item);
    console.log();
  }
}

Delete a resource

The following function deletes the specified resource from the given resource group.

async function delete_resource(client, resource_name) {
  console.log("Deleting resource: " + resource_name + "...");
  await client.beginDeleteAndWait(resource_group_name, resource_name);
  console.log("Resource deleted.");
  console.log();
}

If you need to recover a deleted resource, see Recover deleted Cognitive Services resources.

Run the application

Add the following code to the bottom of your script to call your main quickstart function with error handling.

try {
  quickstart();
} catch (error) {
  console.log(error);
}

Then, in your console window, run the application with the node command.

node index.js

See also

Reference documentation | Library source code | Package (PyPi) | Samples

Python prerequisites

  • A valid Azure subscription - Create one for free.
  • Python 3.x
  • Your Azure account must have a Cognitive Services Contributor role assigned in order for you to agree to the responsible AI terms and create a resource. To get this role assigned to your account, follow the steps in the Assign roles documentation, or contact your administrator.
  • You must create your first Face, Language service, or Computer Vision resources from the Azure portal to review and acknowledge the terms and conditions. You can do so here: Face, Language service, Computer Vision. After that, you can create subsequent resources using any deployment tool (SDK, CLI, or ARM template, etc) under the same Azure subscription.

Create an Azure Service Principal

To have your application interact with your Azure account, you need an Azure service principal to manage permissions. Follow the instructions in Create an Azure service principal.

When you create a service principal, you'll see it has a secret value, an ID, and an application ID. Save the application ID and secret to a temporary location for later steps.

Create a resource group

Before you create a Cognitive Services resource, your account must have an Azure resource group to contain the resource. If you don't already have a resource group, create one in the Azure portal before continuing.

Create a new Python application

Create a new Python application in your preferred editor or IDE and navigate to your project in a console window.

Install the client library

You can install the client library with:

pip install azure-mgmt-cognitiveservices

If you're using the Visual Studio IDE, the client library is available as a downloadable NuGet package.

Import libraries

Open your Python script and import the following libraries.

import time
from azure.identity import ClientSecretCredential
from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient
from azure.mgmt.cognitiveservices.models import Account, Sku

Authenticate the client

Add the following fields to the root of your script and fill in their values, using the service principal you created and your Azure account information.

# Be sure to use the service pricipal application ID, not simply the ID. 
service_principal_application_id = "PASTE_YOUR_SERVICE_PRINCIPAL_APPLICATION_ID_HERE"
service_principal_secret = "PASTE_YOUR_SERVICE_PRINCIPAL_SECRET_HERE"

# The ID of your Azure subscription. You can find this in the Azure Dashboard under Home > Subscriptions.
subscription_id = "PASTE_YOUR_SUBSCRIPTION_ID_HERE"

# The Active Directory tenant ID. You can find this in the Azure Dashboard under Home > Azure Active Directory.
tenant_id = "PASTE_YOUR_TENANT_ID_HERE"

# The name of the Azure resource group in which you want to create the resource.
# You can find resource groups in the Azure Dashboard under Home > Resource groups.
resource_group_name = "PASTE_YOUR_RESOURCE_GROUP_NAME_HERE"

# The name of the custom subdomain to use when you create the resource. This is optional.
# For example, if you create a Bing Search v7 resource with the custom subdomain name 'my-search-resource',
# your resource would have the endpoint https://my-search-resource.cognitiveservices.azure.com/.
# Note not all Cognitive Services allow custom subdomain names.
subdomain_name = "PASTE_YOUR_SUBDOMAIN_NAME_HERE"

# How many seconds to wait between checking the status of an async operation.
wait_time = 10

Then add the following code to construct a CognitiveServicesManagementClient object. This object is needed for all of your Azure management operations.

credential = ClientSecretCredential(tenant_id, service_principal_application_id, service_principal_secret)
client = CognitiveServicesManagementClient(credential, subscription_id)

Create a Cognitive Services resource (Python)

To create and subscribe to a new Cognitive Services resource, use the Create function. This function adds a new billable resource to the resource group you pass in. When you create your new resource, you'll need to know the "kind" of service you want to use, along with its pricing tier (or SKU) and an Azure location. The following function takes all of these arguments and creates a resource.

def create_resource (resource_name, kind, sku_name, location) :
    print("Creating resource: " + resource_name + "...")

# NOTE If you do not want to use a custom subdomain name, remove the customSubDomainName
# property from the properties object.
    parameters = Account(sku=Sku(name=sku_name), kind=kind, location=location, properties={ 'custom_sub_domain_name' : subdomain_name })

    poller = client.accounts.begin_create(resource_group_name, resource_name, parameters)
    while (False == poller.done ()) :
        print ("Waiting {wait_time} seconds for operation to finish.".format (wait_time = wait_time))
        time.sleep (wait_time)
# This will raise an exception if the server responded with an error.
    result = poller.result ()

    print("Resource created.")
    print()
    print("ID: " + result.id)
    print("Name: " + result.name)
    print("Type: " + result.type)
    print()

Choose a service and pricing tier

When you create a new resource, you'll need to know the "kind" of service you want to use, along with the pricing tier (or SKU) you want. You'll use this and other information as parameters when creating the resource. The following function lists the available Cognitive Service "kinds."

def list_available_kinds_skus_locations():
    print("Available SKUs:")
    result = client.resource_skus.list()
    print("Kind\tSKU Name\tSKU Tier\tLocations")
    for x in result:
        locations = ",".join(x.locations)
        print(x.kind + "\t" + x.name + "\t" + x.tier + "\t" + locations)

You can access Azure Cognitive Services through two different resources: A multi-service resource, or a single-service one.

  • Multi-service resource:
    • Access multiple Azure Cognitive Services with a single key and endpoint.
    • Consolidates billing from the services you use.
  • Single-service resource:
    • Access a single Azure Cognitive Service with a unique key and endpoint for each service created.
    • Use the free tier to try out the service.

See the list of SKUs and pricing information below.

Multi-service

Service Kind
Multiple services. For more information, see the pricing page. CognitiveServices

Vision

Service Kind
Computer Vision ComputerVision
Custom Vision - Prediction CustomVision.Prediction
Custom Vision - Training CustomVision.Training
Face Face
Form Recognizer FormRecognizer

Speech

Service Kind
Speech Services SpeechServices

Language

Service Kind
LUIS LUIS
QnA Maker QnAMaker
Language service TextAnalytics
Text Translation TextTranslation

Decision

Service Kind
Anomaly Detector AnomalyDetector
Content Moderator ContentModerator
Personalizer Personalizer

Pricing tiers and billing

Pricing tiers (and the amount you get billed) are based on the number of transactions you send using your authentication information. Each pricing tier specifies the:

  • maximum number of allowed transactions per second (TPS).
  • service features enabled within the pricing tier.
  • cost for a predefined number of transactions. Going above this number will cause an extra charge as specified in the pricing details for your service.

Note

Many of the Cognitive Services have a free tier you can use to try the service. To use the free tier, use F0 as the SKU for your resource.

View your resources

To view all of the resources under your Azure account (across all resource groups), use the following function:

def list_resources():
    print("Resources in resource group: " + resource_group_name)
    result = client.accounts.list_by_resource_group(resource_group_name)
    for x in result:
        print(x.name)
        print(x)
        print()

Delete a resource

The following function deletes the specified resource from the given resource group.

def delete_resource(resource_name) :
    print("Deleting resource: " + resource_name + "...")

    poller = client.accounts.begin_delete(resource_group_name, resource_name)
    while (False == poller.done ()) :
        print ("Waiting {wait_time} seconds for operation to finish.".format (wait_time = wait_time))
        time.sleep (wait_time)
# This will raise an exception if the server responded with an error.
    result = poller.result ()

    print("Resource deleted.")

If you need to recover a deleted resource, see Recover deleted Cognitive Services resources.

Call management functions

Add the following code to the bottom of your script to call the above functions. This code lists available resources, creates a sample resource, lists your owned resources, and then deletes the sample resource.

resource_name = "test_resource"
resource_kind = "TextTranslation"
resource_sku = "F0"
resource_location = "Global"

# Uncomment this to list all available resource kinds, SKUs, and locations for your Azure account.
#list_available_kinds_skus_locations ()

# Create a resource with kind Text Translation, SKU F0 (free tier), location global.
create_resource(resource_name, resource_kind, resource_sku, resource_location)

# Uncomment this to list all resources for your Azure account.
#list_resources()

# Delete the resource.
delete_resource(resource_name)

# NOTE: Deleting a resource only soft-deletes it. To delete it permanently, you must purge it.
# Otherwise, if you later try to create a resource with the same name, you will receive the following error:
# azure.core.exceptions.ResourceExistsError: (FlagMustBeSetForRestore) An existing resource with ID '<your resource ID>' has been soft-deleted. To restore the resource, you must specify 'restore' to be 'true' in the property. If you don't want to restore existing resource, please purge it first.
# Code: FlagMustBeSetForRestore

# Purge the resource.
purge_resource(resource_name, resource_location)

Run the application

Run your application from the command line with the python command.

python <your-script-name>.py

See also