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 is a family of cloud-base services with REST APIs and client libraries available to help developers build cognitive intelligence into their applications. Developers do not need direct artificial intelligence (AI) or data science skills or knowledge to achieve success. Azure Cognitive Services enables developers to easily add cognitive features into their applications with cognitive solutions that can see, hear, speak, understand, and even begin to reason.

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

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, account_tier, 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
Service Kind
Bing Autosuggest Bing.Autosuggest.v7
Bing Custom Search Bing.CustomSearch
Bing Entity Search Bing.EntitySearch
Bing Search Bing.Search.v7
Bing Spell Check Bing.SpellCheck.v7

Speech

Service Kind
Speech Services SpeechServices
Speech Recognition SpeakerRecognition

Language

Service Kind
LUIS LUIS
QnA Maker QnAMaker
Text Analytics 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();
}

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

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.microsoft.azure.*;
import com.microsoft.azure.arm.resources.Region;
import com.microsoft.azure.credentials.*;
import com.microsoft.azure.management.cognitiveservices.v2017_04_18.*;
import com.microsoft.azure.management.cognitiveservices.v2017_04_18.implementation.*;

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 = "INSERT APPLICATION ID HERE";
private static String applicationSecret = "INSERT APPLICATION SECRET HERE";

/* The ID of your Azure subscription. You can find this in the Azure Dashboard under Home > Subscriptions. */
private static String subscriptionId = "INSERT 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 = "INSERT 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 = "INSERT 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.

ApplicationTokenCredentials credentials = new ApplicationTokenCredentials(applicationId, tenantId, applicationSecret, AzureEnvironment.AZURE);

CognitiveServicesManager client = CognitiveServicesManager.authenticate(credentials, subscriptionId);

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 Text Translation, SKU F0 (free tier), location global.
String resourceId = create_resource (client, "test_resource", resourceGroupName, "TextAnalytics", "F0", Region.US_WEST);

// list all resources for your Azure account.
list_resources (client);

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

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 kind, String skuName, Region region) {
        System.out.println ("Creating resource: " + resourceName + "...");

/* NOTE If you do not want to use a custom subdomain name, remove the withCustomSubDomainName
setter from the CognitiveServicesAccountProperties object. */
        CognitiveServicesAccount result = client.accounts().define(resourceName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroupName)
            .withKind(kind)
            .withSku(new Sku().withName(skuName))
            .withProperties(new CognitiveServicesAccountProperties().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();
    // See https://github.com/ReactiveX/RxJava/wiki/Blocking-Observable-Operators
    for (ResourceSku sku : skus.listAsync().toBlocking().toIterable()) {
        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
Service Kind
Bing Autosuggest Bing.Autosuggest.v7
Bing Custom Search Bing.CustomSearch
Bing Entity Search Bing.EntitySearch
Bing Search Bing.Search.v7
Bing Spell Check Bing.SpellCheck.v7

Speech

Service Kind
Speech Services SpeechServices
Speech Recognition SpeakerRecognition

Language

Service Kind
LUIS LUIS
QnA Maker QnAMaker
Text Analytics 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) {
    System.out.println ("Resources in resource group: " + resourceGroupName);
    // Note Azure resources are also sometimes referred to as accounts.
    Accounts accounts = client.accounts();
    for (CognitiveServicesAccount account : accounts.listByResourceGroupAsync(resourceGroupName).toBlocking().toIterable()) {
        System.out.println ("Kind: " + account.kind ());
        System.out.println ("SKU Name: " + account.sku().name());
        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().deleteByIds (resourceId);
    System.out.println ("Resource deleted.");
    System.out.println ();
}

See also

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

JavaScript prerequisites

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/ms-rest-js
npm install @azure/ms-rest-nodeauth

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
 * npm install @azure/ms-rest-js
 * npm install @azure/ms-rest-nodeauth
 */
var Arm = require("@azure/arm-cognitiveservices");
var msRestNodeAuth = require("@azure/ms-rest-nodeauth");

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() {
    const credentials = await msRestNodeAuth.loginWithServicePrincipalSecret (service_principal_application_id, service_principal_secret, tenant_id);
    const client = new Arm.CognitiveServicesManagementClient (credentials, subscription_id);
    // Note Azure resources are also sometimes referred to as accounts.
    const accounts_client = new Arm.Accounts (client);
    const resource_skus_client = new Arm.ResourceSkus (client);

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, kind, sku_name, location) {
    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: sku_name }, kind : kind, location : location, properties : { customSubDomainName : subdomain_name } };
    return client.create(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 = await client.list ();
    console.log("Kind\tSKU Name\tSKU Tier\tLocations");
    result.forEach (function (x) {
        var locations = x.locations.join(",");
        console.log(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
Service Kind
Bing Autosuggest Bing.Autosuggest.v7
Bing Custom Search Bing.CustomSearch
Bing Entity Search Bing.EntitySearch
Bing Search Bing.Search.v7
Bing Spell Check Bing.SpellCheck.v7

Speech

Service Kind
Speech Services SpeechServices
Speech Recognition SpeakerRecognition

Language

Service Kind
LUIS LUIS
QnA Maker QnAMaker
Text Analytics 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 = await client.listByResourceGroup (resource_group_name);
    result.forEach (function (x) {
        console.log(x);
        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.deleteMethod (resource_group_name, resource_name)
    console.log ("Resource deleted.");
    console.log ();
}

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

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.

from azure.identity import ClientSecretCredential
from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient
from azure.mgmt.cognitiveservices.models import CognitiveServicesAccount, 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"

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 = CognitiveServicesAccount(sku=Sku(name=sku_name), kind=kind, location=location, properties={ 'custom_sub_domain_name' : subdomain_name })
    result = client.accounts.create(resource_group_name, resource_name, parameters)
    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
Service Kind
Bing Autosuggest Bing.Autosuggest.v7
Bing Custom Search Bing.CustomSearch
Bing Entity Search Bing.EntitySearch
Bing Search Bing.Search.v7
Bing Spell Check Bing.SpellCheck.v7

Speech

Service Kind
Speech Services SpeechServices
Speech Recognition SpeakerRecognition

Language

Service Kind
LUIS LUIS
QnA Maker QnAMaker
Text Analytics 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)
        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 + "...")
    client.accounts.delete(resource_group_name, resource_name)
    print("Resource deleted.")

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.

# 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("test_resource", "TextTranslation", "F0", "Global")

# List all resources for your Azure account.
list_resources()

# Delete the resource.
delete_resource("test_resource")

Run the application

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

python <your-script-name>.py

See also