Getting started overview
Getting started with Microsoft Azure Cognitive Services involves a sequence of steps to provision resources, obtain necessary credentials, and execute an initial API call. The process begins with establishing an Azure account, followed by the creation of a Cognitive Services resource within the Azure portal. This resource acts as the access point for various AI models, such as those for vision, speech, or language processing. Upon creation, users are provided with an API key and an endpoint URL, which are fundamental for authenticating all subsequent requests to the services. Developers can then choose to interact with the services directly via REST APIs or utilize one of the available client library SDKs in languages like Python, JavaScript, Java, .NET, or Go to streamline integration into their applications.
The foundational steps include:
- Azure Account Setup: Creating or logging into an existing Microsoft Azure account.
- Resource Creation: Setting up an Azure Cognitive Services resource in the Azure portal.
- Credential Retrieval: Locating the API key and endpoint URL associated with the newly created resource.
- First Request: Making a test call to a Cognitive Service using the obtained credentials, either through a REST client or one of the official SDKs.
Quick Reference Guide
| Step | What to do | Where |
|---|---|---|
| 1. Sign up/in | Create or use an Azure account | Azure AI Services homepage |
| 2. Create Resource | Provision a Cognitive Services resource | Azure portal |
| 3. Get Credentials | Retrieve API Key and Endpoint | Azure portal (Keys and Endpoint section) |
| 4. Make Request | Send your first API call | Azure Language Service quickstart or chosen SDK documentation |
Create an account and get keys
To begin using Azure Cognitive Services, an Azure account is required. If you do not have one, you can sign up on the Azure homepage. Azure offers a free tier for many Cognitive Services, allowing developers to experiment with limited transactions without incurring costs.
After logging into your Azure account, the next step is to create a Cognitive Services resource. This resource serves as a unified access point for multiple AI capabilities or can be specific to a single service (e.g., Language, Vision). The process is as follows:
- Navigate to the Azure portal.
- In the search bar, type
Cognitive Servicesand select Cognitive Services from the results. - Click Create.
- On the Create Cognitive Services page, provide the necessary details:
- Subscription: Choose your Azure subscription.
- Resource Group: Create a new one or select an existing one. Resource groups logically organize Azure resources.
- Region: Select a geographical region close to your users for lower latency.
- Name: Provide a unique name for your resource.
- Pricing tier: Choose a pricing tier. The
Free F0tier is available for initial testing and development. For production use, select a standard tier based on anticipated usage. - Review and click Create.
Once the resource is deployed, you will need to retrieve its API key and endpoint. These are crucial for authenticating your requests to the Cognitive Services. To find them:
- From your newly created Cognitive Services resource in the Azure portal, navigate to the Resource Management section in the left-hand menu.
- Click on Keys and Endpoint.
- You will see two API keys (Key 1 and Key 2) and an Endpoint URL. Copy either Key 1 or Key 2 and the Endpoint. It is advisable to use Key 2 for development and reserve Key 1 for scenarios like key rotation.
Your first request
With your API key and endpoint, you can now make your first request to Azure Cognitive Services. This example demonstrates a basic text analysis operation using the Language service (specifically, sentiment analysis) via a REST API call. Similar steps apply for other services like Vision or Speech, adjusting the endpoint and request body accordingly. For those preferring SDKs, Azure provides client libraries for Python, C#, Java, JavaScript, and Go, significantly simplifying integration.
REST API Example: Sentiment Analysis
This example uses curl, a command-line tool for making HTTP requests:
-
Set Environment Variables (recommended): Store your API key and endpoint to avoid hardcoding them directly in your script or command. Replace
YOUR_API_KEYandYOUR_ENDPOINTwith your actual credentials.export COGNITIVE_SERVICE_KEY="YOUR_API_KEY" export COGNITIVE_SERVICE_ENDPOINT="YOUR_ENDPOINT" -
Construct the Request: The Language service's sentiment analysis API expects a JSON payload containing documents to analyze. The endpoint for sentiment analysis typically looks like
YOUR_ENDPOINT/text/analytics/v3.1/sentiment.curl -X POST "${COGNITIVE_SERVICE_ENDPOINT}language/analyze-text/jobs?api-version=2023-04-01" \ -H "Ocp-Apim-Subscription-Key: ${COGNITIVE_SERVICE_KEY}" \ -H "Content-Type: application/json" \ -d '{ "displayName": "My Sentiment Analysis Job", "analysisInput": { "documents": [ { "id": "1", "language": "en", "text": "The food was delicious and the staff were friendly." }, { "id": "2", "language": "en", "text": "The service was slow, and the coffee was cold." } ] }, "tasks": [ { "kind": "SentimentAnalysis", "parameters": { "modelVersion": "latest" } } ] }' -
Execute and Review: Run the
curlcommand. The response will be a JSON object containing the results of the sentiment analysis for each document, indicating overall sentiment (e.g., positive, negative, neutral) and confidence scores. For asynchronous operations like this job submission, the initial response will provide a status URL to check the job's progress and retrieve final results. You would then use a GET request on the status URL provided in theoperation-locationheader of the initial response.curl -X GET "OPERATION_LOCATION_URL" \ -H "Ocp-Apim-Subscription-Key: ${COGNITIVE_SERVICE_KEY}"
SDK Example: Python Sentiment Analysis
For Python developers, the azure-ai-textanalytics library simplifies interaction:
-
Install the SDK:
pip install azure-ai-textanalytics==5.3.0 -
Write Python code:
import os from azure.core.credentials import AzureKeyCredential from azure.ai.textanalytics import TextAnalyticsClient # Your Cognitive Services key and endpoint key = os.environ.get("COGNITIVE_SERVICE_KEY", "YOUR_API_KEY") endpoint = os.environ.get("COGNITIVE_SERVICE_ENDPOINT", "YOUR_ENDPOINT") # Instantiate the client text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key)) documents = [ "The food was delicious and the staff were friendly.", "The service was slow, and the coffee was cold.", "I had a wonderful time at the park yesterday." ] # Analyze sentiment response = text_analytics_client.analyze_sentiment(documents=documents, show_opinion_mining=True) for doc in response: print(f"Document Text: {doc.text}") print(f"Overall Sentiment: {doc.sentiment}") print("Positive Score: {0:.2f}; Neutral Score: {1:.2f}; Negative Score: {2:.2f}".format( doc.confidence_scores.positive, doc.confidence_scores.neutral, doc.confidence_scores.negative, )) if doc.sentences: for sentence in doc.sentences: print(f" Sentence Sentiment: {sentence.sentiment}") print(" Sentence Confidence Scores: Positive={0:.2f}, Neutral={1:.2f}, Negative={2:.2f}".format( sentence.confidence_scores.positive, sentence.confidence_scores.neutral, sentence.confidence_scores.negative, )) print("\n") -
Run the script: Execute the Python file. The output will display the sentiment analysis results for each document.
Common next steps
After successfully making your first request, consider these common next steps to further integrate and optimize your use of Azure Cognitive Services:
- Explore other services: Azure Cognitive Services offers a wide range of capabilities beyond basic text analysis. Investigate Speech-to-Text, Computer Vision, or other Language service features like entity recognition or key phrase extraction. Each service has its own dedicated documentation and quickstarts.
- Implement client library SDKs: For robust application development, using the official SDKs (Python, .NET, Java, JavaScript, Go) is generally more efficient than direct REST API calls. SDKs handle authentication, error handling, and data serialization, reducing boilerplate code.
- Secure your API keys: Never hardcode API keys in public repositories or client-side code. Utilize environment variables, Azure Key Vault, or other secure methods for managing credentials. Implement OAuth 2.0 or Azure AD authentication where applicable for enhanced security, especially in production environments.
- Monitor usage and costs: Regularly check your Cognitive Services resource in the Azure portal for usage metrics and cost analysis. Set up alerts to avoid unexpected billing.
- Error handling and retry logic: Implement robust error handling and retry logic in your application. Network issues, rate limits, or transient service unavailability can occur. The Azure Architecture Center provides guidance on implementing retry patterns.
- Understand pricing: Review the Cognitive Services pricing page to understand the costs associated with different services and usage tiers. The free tier is suitable for development but has limitations.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting tips for Azure Cognitive Services:
- Check API Key and Endpoint: The most frequent cause of errors is an incorrect API key or endpoint. Double-check that you have copied them accurately from the Azure portal. Ensure the endpoint corresponds to the specific service and region where your resource was created. For example, a Language service endpoint will differ from a Vision service endpoint.
- Verify Headers: For REST API calls, ensure that the
Ocp-Apim-Subscription-Keyheader is correctly set with your API key and theContent-Typeheader is set toapplication/json(or the appropriate type for your request, e.g.,application/octet-streamfor some Vision APIs). - Endpoint Format: Ensure your endpoint URL ends with a trailing slash where required or includes the correct API version (e.g.,
/v3.1/). Refer to the Azure Cognitive Services REST API Reference for specific service endpoints. - Region Mismatch: The endpoint used in your request must match the region where your Cognitive Services resource was provisioned. If your resource is in "East US," your endpoint URL should reflect that region.
- Request Body Format: Confirm that the JSON request body is well-formed and adheres to the expected schema for the specific API you are calling. Syntax errors in JSON can lead to parser errors on the server side.
- Rate Limits: If you are making multiple requests quickly, you might hit rate limits, especially on the free tier. Implement a delay between requests or use a back-off strategy.
- Resource Status: Check the Azure portal to ensure your Cognitive Services resource is active and hasn't been suspended or deleted.
- Firewall or Network Issues: If you are making requests from a restricted network, ensure that outbound connections to Azure Cognitive Services endpoints are not blocked by a firewall or proxy.
- Azure Diagnostics: Utilize Azure Monitor and logging within the Azure portal to view diagnostics and error logs related to your Cognitive Services resource, which can provide more detailed insights into failed requests.