Lab 1: Provision an AI Resource
Building your first AI service
Provision in Azure
- Open up the Azure Portal
- Search for Azure AI Services
- Create a multi-service account
- subscription
- choose your RG or create a new one
- region
- pricing tier is Standard S0
- Wait for this to complete.
Connecting to the AI Service
You connect to a multi-service account using Keys and an Endpoint. These can be found on the Keys and Endpoints tab.
- Take note of the:
- key
- endpoint
- region (some services need this as well)
-
Inside of the lab folder, navigate to the .env file The path for me was
C:\coding\openai\mslearn-ai-services\Labfiles\01-use-azure-ai-services\Python\rest-client\.env
-
Enter in your key and endpoint here and save. Normally you will want to extract these from a Key Vault, but we will learn about that in a later lab.
-
Save the .env file
Using the service using a Rest API
- Open the rest-client.py file and read through it.
rest-client.py
from dotenv import load_dotenv
import os
import http.client, base64, json, urllib
from urllib import request, parse, error
def main():
global ai_endpoint
global ai_key
try:
# Get Configuration Settings
load_dotenv()
ai_endpoint = os.getenv('AI_SERVICE_ENDPOINT')
ai_key = os.getenv('AI_SERVICE_KEY')
# Get user input (until they enter "quit")
userText =''
while userText.lower() != 'quit':
userText = input('Enter some text ("quit" to stop)\n')
if userText.lower() != 'quit':
GetLanguage(userText)
except Exception as ex:
print(ex)
def GetLanguage(text):
try:
# Construct the JSON request body (a collection of documents, each with an ID and text)
jsonBody = {
"documents":[
{"id": 1,
"text": text}
]
}
# Let's take a look at the JSON we'll send to the service
print(json.dumps(jsonBody, indent=2))
# Make an HTTP request to the REST interface
uri = ai_endpoint.rstrip('/').replace('https://', '')
conn = http.client.HTTPSConnection(uri)
# Add the authentication key to the request header
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': ai_key
}
# Use the Text Analytics language API
conn.request("POST", "/text/analytics/v3.1/languages?", str(jsonBody).encode('utf-8'), headers)
# Send the request
response = conn.getresponse()
data = response.read().decode("UTF-8")
# If the call was successful, get the response
if response.status == 200:
# Display the JSON response in full (just so we can see it)
results = json.loads(data)
print(json.dumps(results, indent=2))
# Extract the detected language name for each document
for document in results["documents"]:
print("\nLanguage:", document["detectedLanguage"]["name"])
else:
# Something went wrong, write the whole response
print(data)
conn.close()
except Exception as ex:
print(ex)
if __name__ == "__main__":
main()
-
Run this file by running
python rest-client.py
-
Enter in some text and it will predict what language it is.
- Type
quit
to exit as the instructions show.
Using the service using an SDK
An SDK will be more powerful than using the REST APIs