Azure Cognitive Services Management Client
This library provides the management client for Azure Cognitive Services, enabling programmatic creation, configuration, and deletion of Cognitive Services accounts (e.g., for Text Analytics, Speech, Vision, Language) within an Azure subscription. It is part of the Azure SDK for Python, currently at version 14.1.0, and receives regular updates as part of the broader Azure SDK.
Common errors
-
ModuleNotFoundError: No module named 'azure.mgmt.cognitiveservices'
cause The `azure-mgmt-cognitiveservices` package is either not installed, or the Python environment where the code is run does not have access to the installed package.fixEnsure the package is correctly installed using pip: `pip install azure-mgmt-cognitiveservices` -
azure.core.exceptions.ClientAuthenticationError: Operation returned an invalid status 'Unauthorized'
cause The credentials provided to the `CognitiveServicesManagementClient` are invalid, expired, or lack the necessary permissions to perform the requested operation on the Azure subscription.fixVerify that your Azure credentials (e.g., environment variables for `DefaultAzureCredential`, service principal details) are correctly configured and that the associated identity has the 'Cognitive Services Contributor' or appropriate role-based access control (RBAC) permissions on the target subscription or resource group. Ensure `az login` is run if using AzureCliCredential. -
AttributeError: 'CognitiveServicesManagementClient' object has no attribute 'deployments'
cause The `deployments` attribute or the specific method you are trying to call may not exist in the version of `azure-mgmt-cognitiveservices` you are using, or it might be located under a different client object or a sub-attribute (e.g., if it moved to a dedicated 'deployments' operations group or a different management client). This is particularly common with API changes across library versions.fixCheck the official Azure SDK for Python documentation for `azure-mgmt-cognitiveservices` (version 14.1.0) to confirm the correct attribute and method names for managing deployments. If using an older version, update the library to the latest stable release: `pip install --upgrade azure-mgmt-cognitiveservices` and adjust your code according to the updated API. For deployments, it's often `client.deployments.begin_create_or_update` or `client.deployments.list`. -
Resource not found
cause This generic 'Resource not found' error (often accompanied by a 404 HTTP status code) indicates that the Azure resource (e.g., Cognitive Services account, resource group, or a specific deployment within it) specified in your request could not be found. This often happens due to incorrect resource names, IDs, subscription IDs, resource group names, or location mismatches.fixDouble-check all resource identifiers (subscription ID, resource group name, account name, deployment name) for typos and ensure they exist in the specified Azure subscription and region. Verify that the authenticated identity has permission to view the resource. -
Cannot modify resource ... because the resource entity provisioning state is not terminal. Please wait for the provisioning state to become terminal and then retry the request.
cause This error occurs when an Azure resource (such as a Cognitive Services account) is in an intermediate provisioning state (e.g., 'Creating', 'Updating', 'Deleting') and cannot accept further modification or deletion requests until its provisioning operation has completed and reached a terminal state ('Succeeded', 'Failed', or 'Canceled').fixWait for the ongoing provisioning operation on the resource to complete before attempting any further modifications or deletions. You can check the resource's provisioning state in the Azure portal or via Azure CLI/SDK. If stuck, consider using `--no-wait` with Azure CLI delete commands, or checking for resource locks.
Warnings
- breaking Authentication mechanisms have significantly evolved in Azure SDK for Python. Older libraries used `ServicePrincipalCredentials` or similar direct credential objects. Modern SDKs (like `azure-mgmt-cognitiveservices` v14.x) primarily use `azure-identity` with `DefaultAzureCredential` for a unified and more secure authentication experience.
- gotcha This library (`azure-mgmt-cognitiveservices`) is a 'control plane' client, used for managing (creating, deleting, configuring) Cognitive Services *accounts*. It is NOT for interacting with the Cognitive Services APIs themselves (e.g., performing text analysis, speech-to-text, or computer vision tasks).
- gotcha Many resource creation/deletion operations in Azure management clients are long-running operations (LROs). Methods like `begin_create()` or `begin_delete()` return a poller object, not the final resource.
- gotcha Cognitive Services account names must be globally unique across Azure, not just within your subscription or resource group, for some service kinds.
Install
-
pip install azure-mgmt-cognitiveservices azure-identity
Imports
- CognitiveServicesManagementClient
from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient
- DefaultAzureCredential
from azure.identity import DefaultAzureCredential
Quickstart
import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.cognitiveservices import CognitiveServicesManagementClient
# Ensure these environment variables are set:
# AZURE_SUBSCRIPTION_ID
# AZURE_RESOURCE_GROUP_NAME (e.g., 'myResourceGroup')
# AZURE_LOCATION (e.g., 'eastus')
subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "")
resource_group_name = os.environ.get("AZURE_RESOURCE_GROUP_NAME", "")
location = os.environ.get("AZURE_LOCATION", "eastus")
account_name = "myunique_cogsrv_account" # Must be globally unique for some services
if not all([subscription_id, resource_group_name]):
raise ValueError("Please set AZURE_SUBSCRIPTION_ID and AZURE_RESOURCE_GROUP_NAME environment variables.")
# Authenticate with Azure
credential = DefaultAzureCredential()
# Create Cognitive Services Management Client
client = CognitiveServicesManagementClient(credential, subscription_id)
print(f"Listing Cognitive Services accounts in resource group '{resource_group_name}':")
for account in client.accounts.list_by_resource_group(resource_group_name):
print(f"- {account.name} (Kind: {account.kind}, Location: {account.location})")
# Example: Create a new account (if it doesn't exist)
print(f"\nAttempting to create/update account '{account_name}'...")
account_properties = {
"sku": {"name": "F0"}, # F0 is the free tier
"kind": "TextAnalytics", # Example kind: 'TextAnalytics', 'Face', 'SpeechServices'
"location": location,
"properties": {}
}
try:
# begin_create returns a poller for long-running operations
poller = client.accounts.begin_create(
resource_group_name,
account_name,
account_properties
)
new_account = poller.result() # Wait for the operation to complete
print(f"Successfully created/updated account: {new_account.name} (ID: {new_account.id})")
except Exception as e:
print(f"Error creating/updating account: {e}")