├── .gitignore ├── Instructions ├── Exercises │ ├── 01-use-azure-ai-services.md │ ├── 02-ai-services-security.md │ ├── 03-monitor-ai-services.md │ ├── 04-use-a-container.md │ └── 05-implement-content-safety.md ├── Labs │ ├── 01-use-azure-ai-services.md │ ├── 02-ai-services-security.md │ ├── 03-monitor-ai-services.md │ ├── 04-use-a-container.md │ └── 05-implement-content-safety.md ├── media │ ├── ai-personalizer │ │ ├── 7-chart2.png │ │ ├── 7-evaluation-form.png │ │ ├── 7-offline-eval-result.png │ │ ├── 8-create-metric-chart.png │ │ ├── 8-install-enable-extensions-code.png │ │ ├── 8-press-run.png │ │ ├── copy-key-endpoint.png │ │ └── create-personalizer-portal.png │ └── cloudshell-launch-portal.png └── setup.md ├── LICENSE ├── Labfiles ├── 01-use-azure-ai-services │ ├── C-Sharp │ │ ├── readme.txt │ │ ├── rest-client │ │ │ ├── Program.cs │ │ │ ├── appsettings.json │ │ │ └── rest_client.csproj │ │ └── sdk-client │ │ │ ├── Program.cs │ │ │ ├── appsettings.json │ │ │ └── sdk-client.csproj │ └── Python │ │ ├── readme.txt │ │ ├── rest-client │ │ ├── .env │ │ └── rest-client.py │ │ └── sdk-client │ │ ├── .env │ │ └── sdk-client.py ├── 02-ai-services-security │ ├── C-Sharp │ │ ├── keyvault_client │ │ │ ├── Program.cs │ │ │ ├── appsettings.json │ │ │ └── keyvault_client.csproj │ │ └── readme.txt │ ├── Python │ │ ├── keyvault_client │ │ │ ├── .env │ │ │ └── keyvault-client.py │ │ └── readme.txt │ ├── rest-test.cmd │ └── rest-test.sh ├── 03-monitor-ai-services │ ├── rest-test.cmd │ └── rest-test.sh ├── 04-use-a-container │ └── rest-test.cmd └── 05-implement-content-safety │ ├── C-Sharp │ ├── Program.cs │ ├── prompt_shield.csproj │ └── readme.txt │ └── Python │ ├── prompt-shield.py │ └── readme.txt ├── README.md ├── _build.yml ├── _config.yml └── index.md /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | obj 3 | *.sln -------------------------------------------------------------------------------- /Instructions/Exercises/01-use-azure-ai-services.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Get Started with Azure AI Services' 4 | module: 'Module 2 - Developing AI Apps with Azure AI Services' 5 | --- 6 | 7 | # Get Started with Azure AI Services 8 | 9 | In this exercise, you'll get started with Azure AI Services by creating an **Azure AI Services** resource in your Azure subscription and using it from a client application. The goal of the exercise is not to gain expertise in any particular service, but rather to become familiar with a general pattern for provisioning and working with Azure AI services as a developer. 10 | 11 | ## Clone the repository in Visual Studio Code 12 | 13 | You'll develop your code using Visual Studio Code. The code files for your app have been provided in a GitHub repo. 14 | 15 | > **Tip**: If you have already cloned the **mslearn-ai-services** repo, open it in Visual Studio code. Otherwise, follow these steps to clone it to your development environment. 16 | 17 | 1. Start Visual Studio Code. 18 | 2. Open the palette (SHIFT+CTRL+P) and run a **Git: Clone** command to clone the `https://github.com/MicrosoftLearning/mslearn-ai-services` repository to a local folder (it doesn't matter which folder). 19 | 3. When the repository has been cloned, open the folder in Visual Studio Code. 20 | 4. Wait while additional files are installed to support the C# code projects in the repo, if necessary 21 | 22 | > **Note**: If you are prompted to add required assets to build and debug, select **Not Now**. 23 | 24 | 5. Expand the `Labfiles/01-use-azure-ai-services` folder. 25 | 26 | Code for both C# and Python has been provided. Expand the folder of your preferred language. 27 | 28 | ## Provision an Azure AI Services resource 29 | 30 | Azure AI Services are cloud-based services that encapsulate artificial intelligence capabilities you can incorporate into your applications. You can provision individual Azure AI services resources for specific APIs (for example, **Language** or **Vision**), or you can provision a single **Azure AI Services** resource that provides access to multiple Azure AI services APIs through a single endpoint and key. In this case, you'll use a single **Azure AI Services** resource. 31 | 32 | 1. Open the Azure portal at `https://portal.azure.com`, and sign in using the Microsoft account associated with your Azure subscription. 33 | 2. In the top search bar, search for *Azure AI services*, select **Azure AI services multi-service account**, and create a resource with the following settings: 34 | - **Subscription**: *Your Azure subscription* 35 | - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* 36 | - **Region**: *Choose any available region* 37 | - **Name**: *Enter a unique name* 38 | - **Pricing tier**: Standard S0 39 | 3. Select the required checkboxes and create the resource. 40 | 4. Wait for deployment to complete, and then view the deployment details. 41 | 5. Go to the resource and view its **Keys and Endpoint** page. This page contains the information that you will need to connect to your resource and use it from applications you develop. Specifically: 42 | - An HTTP *endpoint* to which client applications can send requests. 43 | - Two *keys* that can be used for authentication (client applications can use either key to authenticate). 44 | - The *location* where the resource is hosted. This is required for requests to some (but not all) APIs. 45 | 46 | ## Use a REST Interface 47 | 48 | The Azure AI services APIs are REST-based, so you can consume them by submitting JSON requests over HTTP. In this example, you'll explore a console application that uses the **Language** REST API to perform language detection; but the basic principle is the same for all of the APIs supported by the Azure AI Services resource. 49 | 50 | > **Note**: In this exercise, you can choose to use the REST API from either **C#** or **Python**. In the steps below, perform the actions appropriate for your preferred language. 51 | 52 | 1. In Visual Studio Code, expand the **C-Sharp** or **Python** folder depending on your language preference. 53 | 2. View the contents of the **rest-client** folder, and note that it contains a file for configuration settings: 54 | 55 | - **C#**: appsettings.json 56 | - **Python**: .env 57 | 58 | Open the configuration file and update the configuration values it contains to reflect the **endpoint** and an authentication **key** for your Azure AI services resource. Save your changes. 59 | 60 | 3. Note that the **rest-client** folder contains a code file for the client application: 61 | 62 | - **C#**: Program.cs 63 | - **Python**: rest-client.py 64 | 65 | Open the code file and review the code it contains, noting the following details: 66 | - Various namespaces are imported to enable HTTP communication 67 | - Code in the **Main** function retrieves the endpoint and key for your Azure AI services resource - these will be used to send REST requests to the Text Analytics service. 68 | - The program accepts user input, and uses the **GetLanguage** function to call the Text Analytics language detection REST API for your Azure AI services endpoint to detect the language of the text that was entered. 69 | - The request sent to the API consists of a JSON object containing the input data - in this case, a collection of **document** objects, each of which has an **id** and **text**. 70 | - The key for your service is included in the request header to authenticate your client application. 71 | - The response from the service is a JSON object, which the client application can parse. 72 | 73 | 4. Right click on the **rest-client** folder, select *Open in Integrated Terminal* and run the following command: 74 | 75 | **C#** 76 | 77 | ``` 78 | dotnet run 79 | ``` 80 | 81 | **Python** 82 | 83 | ``` 84 | pip install python-dotenv 85 | python rest-client.py 86 | ``` 87 | 88 | 5. When prompted, enter some text and review the language that is detected by the service, which is returned in the JSON response. For example, try entering "Hello", "Bonjour", and "Gracias". 89 | 6. When you have finished testing the application, enter "quit" to stop the program. 90 | 91 | ## Use an SDK 92 | 93 | You can write code that consumes Azure AI services REST APIs directly, but there are software development kits (SDKs) for many popular programming languages, including Microsoft C#, Python, Java, and Node.js. Using an SDK can greatly simplify development of applications that consume Azure AI services. 94 | 95 | 1. In Visual Studio Code, expand the **sdk-client** folder under the **C-Sharp** or **Python** folder, depending on your language preference. Then run `cd ../sdk-client` to change into the relevant **sdk-client** folder. 96 | 97 | 2. Install the Text Analytics SDK package by running the appropriate command for your language preference: 98 | 99 | **C#** 100 | 101 | ``` 102 | dotnet add package Azure.AI.TextAnalytics --version 5.3.0 103 | ``` 104 | 105 | **Python** 106 | 107 | ``` 108 | pip install azure-ai-textanalytics==5.3.0 109 | ``` 110 | 111 | 3. View the contents of the **sdk-client** folder, and note that it contains a file for configuration settings: 112 | 113 | - **C#**: appsettings.json 114 | - **Python**: .env 115 | 116 | Open the configuration file and update the configuration values it contains to reflect the **endpoint** and an authentication **key** for your Azure AI services resource. Save your changes. 117 | 118 | 4. Note that the **sdk-client** folder contains a code file for the client application: 119 | 120 | - **C#**: Program.cs 121 | - **Python**: sdk-client.py 122 | 123 | Open the code file and review the code it contains, noting the following details: 124 | - The namespace for the SDK you installed is imported 125 | - Code in the **Main** function retrieves the endpoint and key for your Azure AI services resource - these will be used with the SDK to create a client for the Text Analytics service. 126 | - The **GetLanguage** function uses the SDK to create a client for the service, and then uses the client to detect the language of the text that was entered. 127 | 128 | 5. Return to the terminal, ensure you are in the **sdk-client** folder, and enter the following command to run the program: 129 | 130 | **C#** 131 | 132 | ``` 133 | dotnet run 134 | ``` 135 | 136 | **Python** 137 | 138 | ``` 139 | python sdk-client.py 140 | ``` 141 | 142 | 6. When prompted, enter some text and review the language that is detected by the service. For example, try entering "Goodbye", "Au revoir", and "Hasta la vista". 143 | 7. When you have finished testing the application, enter "quit" to stop the program. 144 | 145 | > **Note**: Some languages that require Unicode character sets may not be recognized in this simple console application. 146 | 147 | ## Clean up resources 148 | 149 | If you're not using the Azure resources created in this lab for other training modules, you can delete them to avoid incurring further charges. 150 | 151 | 1. Open the Azure portal at `https://portal.azure.com`, and in the top search bar, search for the resources you created in this lab. 152 | 153 | 2. On the resource page, select **Delete** and follow the instructions to delete the resource. Alternatively, you can delete the entire resource group to clean up all resources at the same time. 154 | 155 | ## More information 156 | 157 | For more information about Azure AI Services, see the [Azure AI Services documentation](https://docs.microsoft.com/azure/ai-services/what-are-ai-services). 158 | -------------------------------------------------------------------------------- /Instructions/Exercises/02-ai-services-security.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Manage Azure AI Services Security' 4 | module: 'Module 2 - Developing AI Apps with Azure AI Services' 5 | --- 6 | 7 | # Manage Azure AI Services Security 8 | 9 | Security is a critical consideration for any application, and as a developer you should ensure that access to resources such as Azure AI services is restricted to only those who require it. 10 | 11 | Access to Azure AI services is typically controlled through authentication keys, which are generated when you initially create an Azure AI services resource. 12 | 13 | ## Clone the repository in Visual Studio Code 14 | 15 | You'll develop your code using Visual Studio Code. The code files for your app have been provided in a GitHub repo. 16 | 17 | > **Tip**: If you have already cloned the **mslearn-ai-services** repo recently, open it in Visual Studio code. Otherwise, follow these steps to clone it to your development environment. 18 | 19 | 1. Start Visual Studio Code. 20 | 2. Open the palette (SHIFT+CTRL+P) and run a **Git: Clone** command to clone the `https://github.com/MicrosoftLearning/mslearn-ai-services` repository to a local folder (it doesn't matter which folder). 21 | 3. When the repository has been cloned, open the folder in Visual Studio Code. 22 | 4. Wait while additional files are installed to support the C# code projects in the repo, if necessary 23 | 24 | > **Note**: If you are prompted to add required assets to build and debug, select **Not Now**. 25 | 26 | 5. Expand the `Labfiles/02-ai-services-security` folder. 27 | 28 | Code for both C# and Python has been provided. Expand the folder of your preferred language. 29 | 30 | ## Provision an Azure AI Services resource 31 | 32 | If you don't already have one in your subscription, you'll need to provision an **Azure AI Services** resource. 33 | 34 | 1. Open the Azure portal at `https://portal.azure.com`, and sign in using the Microsoft account associated with your Azure subscription. 35 | 2. In the top search bar, search for *Azure AI services*, select **Azure AI services multi-service account**, and create a resource with the following settings: 36 | - **Subscription**: *Your Azure subscription* 37 | - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* 38 | - **Region**: *Choose any available region* 39 | - **Name**: *Enter a unique name* 40 | - **Pricing tier**: Standard S0 41 | 3. Select the required checkboxes and create the resource. 42 | 4. Wait for deployment to complete, and then view the deployment details. 43 | 44 | ## Manage authentication keys 45 | 46 | When you created your Azure AI services resource, two authentication keys were generated. You can manage these in the Azure portal or by using the Azure command line interface (CLI). 47 | 48 | 1. Choose one method of obtaining your authentication keys and endpoint: 49 | 50 | **Using the Azure portal**: In the Azure portal, go to your Azure AI services resource and view its **Keys and Endpoint** page. This page contains the information that you will need to connect to your resource and use it from applications you develop. Specifically: 51 | - An HTTP *endpoint* to which client applications can send requests. 52 | - Two *keys* that can be used for authentication (client applications can use either of the keys. A common practice is to use one for development, and another for production. You can easily regenerate the development key after developers have finished their work to prevent continued access). 53 | - The *location* where the resource is hosted. This is required for requests to some (but not all) APIs. 54 | 55 | **Using the Command Line**: Alternatively you can use the following command to get the list of Azure AI services keys. In Visual Studio Code, open a new terminal. Then paste in the following command; replacing *<resourceName>* with the name of your Azure AI services resource, and *<resourceGroup>* with the name of the resource group in which you created it. 56 | 57 | ``` 58 | az cognitiveservices account keys list --name --resource-group 59 | ``` 60 | 61 | The command returns a list of the keys for your Azure AI services resource - there are two keys, named **key1** and **key2**. 62 | 63 | > **Tip**: If you haven't authenticated Azure CLI yet, first run `az login` and sign into your account. 64 | 65 | 2. To test your Azure AI service, you can use **curl** - a command line tool for HTTP requests. In the **02-ai-services-security** folder, open **rest-test.cmd** and edit the **curl** command it contains (shown below), replacing *<yourEndpoint>* and *<yourKey>* with your endpoint URI and **Key1** key to use the Analyze Text API in your Azure AI services resource. 66 | 67 | ```bash 68 | curl -X POST "/language/:analyze-text?api-version=2023-04-01" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: " --data-ascii "{'analysisInput':{'documents':[{'id':1,'text':'hello'}]}, 'kind': 'LanguageDetection'}" 69 | ``` 70 | 71 | 3. Save your changes. In the terminal, navigate to the "02-ai-services-security" folder. (**Note**: you can do this by right clicking on the 02-ai-services-security" folder in your explorer, and selecting *Open in Integrated Terminal*). Then run the following command: 72 | 73 | ``` 74 | ./rest-test.cmd 75 | ``` 76 | 77 | The command returns a JSON document containing information about the language detected in the input data (which should be English). 78 | 79 | 4. If a key becomes compromised, or the developers who have it no longer require access, you can regenerate it in the portal or by using the Azure CLI. Run the following command to regenerate your **key1** key (replacing *<resourceName>* and *<resourceGroup>* for your resource). 80 | 81 | ``` 82 | az cognitiveservices account keys regenerate --name --resource-group --key-name key1 83 | ``` 84 | 85 | The list of keys for your Azure AI services resource is returned - note that **key1** has changed since you last retrieved them. 86 | 87 | 5. Re-run the **rest-test** command with the old key (you can use the **^** arrow on your keyboard to cycle through previous commands), and verify that it now fails. 88 | 6. Edit the *curl* command in **rest-test.cmd** replacing the key with the new **key1** value, and save the changes. Then rerun the **rest-test** command and verify that it succeeds. 89 | 90 | > **Tip**: In this exercise, you used the full names of Azure CLI parameters, such as **--resource-group**. You can also use shorter alternatives, such as **-g**, to make your commands less verbose (but a little harder to understand). The [Azure AI Services CLI command reference](https://docs.microsoft.com/cli/azure/cognitiveservices?view=azure-cli-latest) lists the parameter options for each Azure AI services CLI command. 91 | 92 | ## Secure key access with Azure Key Vault 93 | 94 | You can develop applications that consume Azure AI services by using a key for authentication. However, this means that the application code must be able to obtain the key. One option is to store the key in an environment variable or a configuration file where the application is deployed, but this approach leaves the key vulnerable to unauthorized access. A better approach when developing applications on Azure is to store the key securely in Azure Key Vault, and provide access to the key through a *managed identity* (in other words, a user account used by the application itself). 95 | 96 | ### Create a key vault and add a secret 97 | 98 | First, you need to create a key vault and add a *secret* for the Azure AI services key. 99 | 100 | 1. Make a note of the **key1** value for your Azure AI services resource (or copy it to the clipboard). 101 | 2. In the Azure portal, on the **Home** page, select the **+Create a resource** button, search for *Key Vault*, and create a **Key Vault** resource with the following settings: 102 | 103 | - **Basics** tab 104 | - **Subscription**: *Your Azure subscription* 105 | - **Resource group**: *The same resource group as your Azure AI service resource* 106 | - **Key vault name**: *Enter a unique name* 107 | - **Region**: *The same region as your Azure AI service resource* 108 | - **Pricing tier**: Standard 109 | 110 | - **Access configuration** tab 111 | - **Permission model**: Vault access policy 112 | - Scroll down to the **Access policies** section and select your user using the checkbox on the left. Then select **Review + create**, and select **Create** to create your resource. 113 | 114 | 3. Wait for deployment to complete and then go to your key vault resource. 115 | 4. In the left navigation pane, select **Secrets** (in the Objects section). 116 | 5. Select **+ Generate/Import** and add a new secret with the following settings : 117 | - **Upload options**: Manual 118 | - **Name**: AI-Services-Key *(it's important to match this exactly, because later you'll run code that retrieves the secret based on this name)* 119 | - **Secret value**: *Your **key1** Azure AI services key* 120 | 6. Select **Create**. 121 | 122 | ### Create a service principal 123 | 124 | To access the secret in the key vault, your application must use a service principal that has access to the secret. You'll use the Azure command line interface (CLI) to create the service principal, find its object ID, and grant access to the secret in Azure Vault. 125 | 126 | 1. Run the following Azure CLI command, replacing *<spName>* with a unique suitable name for an application identity (for example, *ai-app* with your initials appended on the end; the name must be unique within your tenant). Also replace *<subscriptionId>* and *<resourceGroup>* with the correct values for your subscription ID and the resource group containing your Azure AI services and key vault resources: 127 | 128 | > **Tip**: If you are unsure of your subscription ID, use the **az account show** command to retrieve your subscription information - the subscription ID is the **id** attribute in the output. If you see an error about the object already existing, please choose a different unique name. 129 | 130 | ``` 131 | az ad sp create-for-rbac -n "api://" --role owner --scopes subscriptions//resourceGroups/ 132 | ``` 133 | 134 | The output of this command includes information about your new service principal. It should look similar to this: 135 | 136 | ``` 137 | { 138 | "appId": "abcd12345efghi67890jklmn", 139 | "displayName": "api://ai-app-", 140 | "password": "1a2b3c4d5e6f7g8h9i0j", 141 | "tenant": "1234abcd5678fghi90jklm" 142 | } 143 | ``` 144 | 145 | Make a note of the **appId**, **password**, and **tenant** values - you will need them later (if you close this terminal, you won't be able to retrieve the password; so it's important to note the values now - you can paste the output into a new text file on your local machine to ensure you can find the values you need later!) 146 | 147 | 2. To get the **object ID** of your service principal, run the following Azure CLI command, replacing *<appId>* with the value of your service principal's app ID. 148 | 149 | ``` 150 | az ad sp show --id 151 | ``` 152 | 153 | 3. Copy the `id` value in the json returned in response. 154 | 3. To assign permission for your new service principal to access secrets in your Key Vault, run the following Azure CLI command, replacing *<keyVaultName>* with the name of your Azure Key Vault resource and *<objectId>* with the value of your service principal's ID value you've just copied. 155 | 156 | ``` 157 | az keyvault set-policy -n --object-id --secret-permissions get list 158 | ``` 159 | 160 | ### Use the service principal in an application 161 | 162 | Now you're ready to use the service principal identity in an application, so it can access the secret Azure AI services key in your key vault and use it to connect to your Azure AI services resource. 163 | 164 | > **Note**: In this exercise, we'll store the service principal credentials in the application configuration and use them to authenticate a **ClientSecretCredential** identity in your application code. This is fine for development and testing, but in a real production application, an administrator would assign a *managed identity* to the application so that it uses the service principal identity to access resources, without caching or storing the password. 165 | 166 | 1. In your terminal, switch to the **C-Sharp** or **Python** folder depending on your language preference by running `cd C-Sharp` or `cd Python`. Then run `cd keyvault_client` to navigate to the app folder. 167 | 2. Install the packages you will need to use for Azure Key Vault and the Text Analytics API in your Azure AI services resource by running the appropriate command for your language preference: 168 | 169 | **C#** 170 | 171 | ``` 172 | dotnet add package Azure.AI.TextAnalytics --version 5.3.0 173 | dotnet add package Azure.Identity --version 1.12.0 174 | dotnet add package Azure.Security.KeyVault.Secrets --version 4.6.0 175 | ``` 176 | 177 | **Python** 178 | 179 | ``` 180 | pip install azure-ai-textanalytics==5.3.0 181 | pip install azure-identity==1.17.1 182 | pip install azure-keyvault-secrets==4.8.0 183 | ``` 184 | 185 | 3. View the contents of the **keyvault-client** folder, and note that it contains a file for configuration settings: 186 | - **C#**: appsettings.json 187 | - **Python**: .env 188 | 189 | Open the configuration file and update the configuration values it contains to reflect the following settings: 190 | 191 | - The **endpoint** for your Azure AI Services resource 192 | - The name of your **Azure Key Vault** resource 193 | - The **tenant** for your service principal 194 | - The **appId** for your service principal 195 | - The **password** for your service principal 196 | 197 | Save your changes by pressing **CTRL+S**. 198 | 4. Note that the **keyvault-client** folder contains a code file for the client application: 199 | 200 | - **C#**: Program.cs 201 | - **Python**: keyvault-client.py 202 | 203 | Open the code file and review the code it contains, noting the following details: 204 | - The namespace for the SDK you installed is imported 205 | - Code in the **Main** function retrieves the application configuration settings, and then it uses the service principal credentials to get the Azure AI services key from the key vault. 206 | - The **GetLanguage** function uses the SDK to create a client for the service, and then uses the client to detect the language of the text that was entered. 207 | 5. Enter the following command to run the program: 208 | 209 | **C#** 210 | 211 | ``` 212 | dotnet run 213 | ``` 214 | 215 | **Python** 216 | 217 | ``` 218 | python keyvault-client.py 219 | ``` 220 | 221 | 6. When prompted, enter some text and review the language that is detected by the service. For example, try entering "Hello", "Bonjour", and "Gracias". 222 | 7. When you have finished testing the application, enter "quit" to stop the program. 223 | 224 | ## Clean up resources 225 | 226 | If you're not using the Azure resources created in this lab for other training modules, you can delete them to avoid incurring further charges. 227 | 228 | 1. Open the Azure portal at `https://portal.azure.com`, and in the top search bar, search for the resources you created in this lab. 229 | 230 | 2. On the resource page, select **Delete** and follow the instructions to delete the resource. Alternatively, you can delete the entire resource group to clean up all resources at the same time. 231 | 232 | ## More information 233 | 234 | For more information about securing Azure AI services, see the [Azure AI Services security documentation](https://docs.microsoft.com/azure/ai-services/security-features). 235 | -------------------------------------------------------------------------------- /Instructions/Exercises/03-monitor-ai-services.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Monitor Azure AI Services' 4 | module: 'Module 2 - Developing AI Apps with Azure AI Services' 5 | --- 6 | 7 | # Monitor Azure AI Services 8 | 9 | Azure AI Services can be a critical part of an overall application infrastructure. It's important to be able to monitor activity and get alerted to issues that may need attention. 10 | 11 | ## Clone the repository in Visual Studio Code 12 | 13 | You'll develop your code using Visual Studio Code. The code files for your app have been provided in a GitHub repo. 14 | 15 | > **Tip**: If you have already cloned the **mslearn-ai-services** repo, open it in Visual Studio code. Otherwise, follow these steps to clone it to your development environment. 16 | 17 | 1. Start Visual Studio Code. 18 | 2. Open the palette (SHIFT+CTRL+P) and run a **Git: Clone** command to clone the `https://github.com/MicrosoftLearning/mslearn-ai-services` repository to a local folder (it doesn't matter which folder). 19 | 3. When the repository has been cloned, open the folder in Visual Studio Code. 20 | 4. Wait while additional files are installed to support the C# code projects in the repo, if necessary 21 | 22 | > **Note**: If you are prompted to add required assets to build and debug, select **Not Now**. 23 | 24 | 5. Expand the `Labfiles/03-monitor-ai-services` folder. 25 | 26 | ## Provision an Azure AI Services resource 27 | 28 | If you don't already have one in your subscription, you'll need to provision an **Azure AI Services** resource. 29 | 30 | 1. Open the Azure portal at `https://portal.azure.com`, and sign in using the Microsoft account associated with your Azure subscription. 31 | 2. In the top search bar, search for *Azure AI services*, select **Azure AI services multi-service account**, and create a resource with the following settings: 32 | - **Subscription**: *Your Azure subscription* 33 | - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* 34 | - **Region**: *Choose any available region* 35 | - **Name**: *Enter a unique name* 36 | - **Pricing tier**: Standard S0 37 | 3. Select any required checkboxes and create the resource. 38 | 4. Wait for deployment to complete, and then view the deployment details. 39 | 5. When the resource has been deployed, go to it and view its **Keys and Endpoint** page. Make a note of the endpoint URI - you will need it later. 40 | 41 | ## Configure an alert 42 | 43 | Let's start monitoring by defining an alert rule so you can detect activity in your Azure AI services resource. 44 | 45 | 1. In the Azure portal, go to your Azure AI services resource and view its **Alerts** page (in the **Monitoring** section). 46 | 2. Select **+ Create** dropdown, and select **Alert rule** 47 | 3. In the **Create an alert rule** page, under **Scope**, verify that the your Azure AI services resource is listed. (Close **Select a signal** pane if open) 48 | 4. Select **Condition** tab, and select on the **See all signals** link to show the **Select a signal** pane that appears on the right, where you can select a signal type to monitor. 49 | 5. In the **Signal type** list, scroll down to the **Activity Log** section, and then select **List Keys (Cognitive Services API Account)**. Then select **Apply**. 50 | 6. Review the activity over the past 6 hours. 51 | 7. Select the **Actions** tab. Note that you can specify an *action group*. This enables you to configure automated actions when an alert is fired - for example, sending an email notification. We won't do that in this exercise; but it can be useful to do this in a production environment. 52 | 8. In the **Details** tab, set the **Alert rule name** to **Key List Alert**. 53 | 9. Select **Review + create**. 54 | 10. Review the configuration for the alert. Select **Create** and wait for the alert rule to be created. 55 | 11. Now you can use the following command to get the list of Azure AI services keys, replacing *<resourceName>* with the name of your Azure AI services resource, and *<resourceGroup>* with the name of the resource group in which you created it. 56 | 57 | ``` 58 | az cognitiveservices account keys list --name --resource-group 59 | ``` 60 | 61 | The command returns a list of the keys for your Azure AI services resource. 62 | 63 | > **Note** If you haven't logged into Azure CLI, you may need to run `az login` before the list keys command will work. 64 | 65 | 12. Switch back to the browser containing the Azure portal, and refresh your **Alerts page**. You should see a **Sev 4** alert listed in the table (if not, wait up to five minutes and refresh again). 66 | 13. Select the alert to see its details. 67 | 68 | ## Visualize a metric 69 | 70 | As well as defining alerts, you can view metrics for your Azure AI services resource to monitor its utilization. 71 | 72 | 1. In the Azure portal, in the page for your Azure AI services resource, select **Metrics** (in the **Monitoring** section). 73 | 2. If there is no existing chart, select **+ New chart**. Then in the **Metric** list, review the possible metrics you can visualize and select **Total Calls**. 74 | 3. In the **Aggregation** list, select **Count**. This will enable you to monitor the total calls to you Azure AI Service resource; which is useful in determining how much the service is being used over a period of time. 75 | 4. To generate some requests to your Azure AI service, you will use **curl** - a command line tool for HTTP requests. In your editor, open **rest-test.cmd** and edit the **curl** command it contains (shown below), replacing *<yourEndpoint>* and *<yourKey>* with your endpoint URI and **Key1** key to use the Text Analytics API in your Azure AI services resource. 76 | 77 | ``` 78 | curl -X POST "/language/:analyze-text?api-version=2023-04-01" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: " --data-ascii "{'analysisInput':{'documents':[{'id':1,'text':'hello'}]}, 'kind': 'LanguageDetection'}" 79 | ``` 80 | 81 | 5. Save your changes and then run the following command: 82 | 83 | ``` 84 | ./rest-test.cmd 85 | ``` 86 | 87 | The command returns a JSON document containing information about the language detected in the input data (which should be English). 88 | 89 | 6. Re-run the **rest-test** command multiple times to generate some call activity (you can use the **^** key to cycle through previous commands). 90 | 7. Return to the **Metrics** page in the Azure portal and refresh the **Total Calls** count chart. It may take a few minutes for the calls you made using *curl* to be reflected in the chart - keep refreshing the chart until it updates to include them. 91 | 92 | ## Clean up resources 93 | 94 | If you're not using the Azure resources created in this lab for other training modules, you can delete them to avoid incurring further charges. 95 | 96 | 1. Open the Azure portal at `https://portal.azure.com`, and in the top search bar, search for the resources you created in this lab. 97 | 98 | 2. On the resource page, select **Delete** and follow the instructions to delete the resource. Alternatively, you can delete the entire resource group to clean up all resources at the same time. 99 | 100 | ## More information 101 | 102 | One of the options for monitoring Azure AI services is to use *diagnostic logging*. Once enabled, diagnostic logging captures rich information about your Azure AI services resource usage, and can be a useful monitoring and debugging tool. It can take over an hour after setting up diagnostic logging to generate any information, which is why we haven't explored it in this exercise; but you can learn more about it in the [Azure AI Services documentation](https://docs.microsoft.com/azure/ai-services/diagnostic-logging). 103 | -------------------------------------------------------------------------------- /Instructions/Exercises/04-use-a-container.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Use an Azure AI Services Container' 4 | module: 'Module 2 - Developing AI Apps with Azure AI Services' 5 | --- 6 | 7 | # Use an Azure AI Services Container 8 | 9 | Using Azure AI services hosted in Azure enables application developers to focus on the infrastructure for their own code while benefiting from scalable services that are managed by Microsoft. However, in many scenarios, organizations require more control over their service infrastructure and the data that is passed between services. 10 | 11 | Many of the Azure AI services APIs can be packaged and deployed in a *container*, enabling organizations to host Azure AI services in their own infrastructure; for example in local Docker servers, Azure Container Instances, or Azure Kubernetes Services clusters. Containerized Azure AI services need to communicate with an Azure-based Azure AI services account to support billing; but application data is not passed to the back-end service, and organizations have greater control over the deployment configuration of their containers, enabling custom solutions for authentication, scalability, and other considerations. 12 | 13 | ## Clone the repository in Visual Studio Code 14 | 15 | You'll develop your code using Visual Studio Code. The code files for your app have been provided in a GitHub repo. 16 | 17 | > **Tip**: If you have already cloned the **mslearn-ai-services** repo, open it in Visual Studio code. Otherwise, follow these steps to clone it to your development environment. 18 | 19 | 1. Start Visual Studio Code. 20 | 2. Open the palette (SHIFT+CTRL+P) and run a **Git: Clone** command to clone the `https://github.com/MicrosoftLearning/mslearn-ai-services` repository to a local folder (it doesn't matter which folder). 21 | 3. When the repository has been cloned, open the folder in Visual Studio Code. 22 | 4. Wait while additional files are installed to support the C# code projects in the repo, if necessary 23 | 24 | > **Note**: If you are prompted to add required assets to build and debug, select **Not Now**. 25 | 26 | 5. Expand the `Labfiles/04-use-a-container` folder. 27 | 28 | ## Provision an Azure AI Services resource 29 | 30 | If you don't already have one in your subscription, you'll need to provision an **Azure AI Services** resource. 31 | 32 | 1. Open the Azure portal at `https://portal.azure.com`, and sign in using the Microsoft account associated with your Azure subscription. 33 | 2. In the top search bar, search for *Azure AI services*, select **Azure AI services multi-service account** and create a resource with the following settings: 34 | - **Subscription**: *Your Azure subscription* 35 | - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* 36 | - **Region**: *Choose any available region* 37 | - **Name**: *Enter a unique name* 38 | - **Pricing tier**: Standard S0 39 | 3. Select the required checkboxes and create the resource. 40 | 4. Wait for deployment to complete, and then view the deployment details. 41 | 5. When the resource has been deployed, go to it and view its **Keys and Endpoint** page. You will need the endpoint and one of the keys from this page in the next procedure. 42 | 43 | ## Deploy and run a Sentiment Analysis container 44 | 45 | Many commonly used Azure AI services APIs are available in container images. For a full list, check out the [Azure AI services documentation](https://learn.microsoft.com/en-us/azure/ai-services/cognitive-services-container-support#containers-in-azure-ai-services). In this exercise, you'll use the container image for the Text Analytics *Sentiment analysis* API; but the principles are the same for all of the available images. 46 | 47 | 1. In the Azure portal, on the **Home** page, select the **+Create a resource** button, search for *container instances*, and create a **Container Instances** resource with the following settings: 48 | 49 | - **Basics**: 50 | - **Subscription**: *Your Azure subscription* 51 | - **Resource group**: *Choose the resource group containing your Azure AI services resource* 52 | - **Container name**: *Enter a unique name* 53 | - **Region**: *Choose any available region* 54 | - **Availability zones**: None 55 | - **SKU**: Standard 56 | - **Image source**: Other Registry 57 | - **Image type**: Public 58 | - **Image**: `mcr.microsoft.com/azure-cognitive-services/textanalytics/sentiment:latest` 59 | - **OS type**: Linux 60 | - **Size**: 1 vcpu, 8 GB memory 61 | - **Networking**: 62 | - **Networking type**: Public 63 | - **DNS name label**: *Enter a unique name for the container endpoint* 64 | - **Ports**: *Change the TCP port from 80 to **5000*** 65 | - **Advanced**: 66 | - **Restart policy**: On failure 67 | - **Environment variables**: 68 | 69 | | Mark as secure | Key | Value | 70 | | -------------- | --- | ----- | 71 | | Yes | `ApiKey` | *Either key for your Azure AI services resource* | 72 | | Yes | `Billing` | *The endpoint URI for your Azure AI services resource* | 73 | | No | `Eula` | `accept` | 74 | 75 | - **Command override**: [ ] 76 | - **Key management**: Microsoft-managed keys (MMK) 77 | - **Tags**: 78 | - *Don't add any tags* 79 | 80 | 2. Select **Review + create** then select **Create**. Wait for deployment to complete, and then go to the deployed resource. 81 | > **Note** Please note that deploying an Azure AI container to Azure Container Instances typically takes 5-10 minutes (provisioning) before they are ready to use. 82 | 3. Observe the following properties of your container instance resource on its **Overview** page: 83 | - **Status**: This should be *Running*. 84 | - **IP Address**: This is the public IP address you can use to access your container instances. 85 | - **FQDN**: This is the *fully-qualified domain name* of the container instances resource, you can use this to access the container instances instead of the IP address. 86 | 87 | > **Note**: In this exercise, you've deployed the Azure AI services container image for sentiment analysis to an Azure Container Instances (ACI) resource. You can use a similar approach to deploy it to a *[Docker](https://www.docker.com/products/docker-desktop)* host on your own computer or network by running the following command (on a single line) to deploy the sentiment analysis container to your local Docker instance, replacing *<yourEndpoint>* and *<yourKey>* with your endpoint URI and either of the keys for your Azure AI services resource. 88 | > The command will look for the image on your local machine, and if it doesn't find it there it will pull it from the *mcr.microsoft.com* image registry and deploy it to your Docker instance. When deployment is complete, the container will start and listen for incoming requests on port 5000. 89 | 90 | ``` 91 | docker run --rm -it -p 5000:5000 --memory 8g --cpus 1 mcr.microsoft.com/azure-cognitive-services/textanalytics/sentiment:latest Eula=accept Billing= ApiKey= 92 | ``` 93 | 94 | ## Use the container 95 | 96 | 1. In your editor, open **rest-test.cmd** and edit the **curl** command it contains (shown below), replacing *<your_ACI_IP_address_or_FQDN>* with the IP address or FQDN for your container. 97 | 98 | ``` 99 | curl -X POST "http://:5000/text/analytics/v3.1/sentiment" -H "Content-Type: application/json" --data-ascii "{'documents':[{'id':1,'text':'The performance was amazing! The sound could have been clearer.'},{'id':2,'text':'The food and service were unacceptable. While the host was nice, the waiter was rude and food was cold.'}]}" 100 | ``` 101 | 102 | 2. Save your changes to the script by pressing **CTRL+S**. Note that you do not need to specify the Azure AI services endpoint or key - the request is processed by the containerized service. The container in turn communicates periodically with the service in Azure to report usage for billing, but does not send request data. 103 | 3. Enter the following command to run the script: 104 | 105 | ``` 106 | ./rest-test.cmd 107 | ``` 108 | 109 | 4. Verify that the command returns a JSON document containing information about the sentiment detected in the two input documents (which should be postive and negative, in that order). 110 | 111 | ## Clean Up 112 | 113 | If you've finished experimenting with your container instance, you should delete it. 114 | 115 | 1. In the Azure portal, open the resource group where you created your resources for this exercise. 116 | 2. Select the container instance resource and delete it. 117 | 118 | ## Clean up resources 119 | 120 | If you're not using the Azure resources created in this lab for other training modules, you can delete them to avoid incurring further charges. 121 | 122 | 1. Open the Azure portal at `https://portal.azure.com`, and in the top search bar, search for the resources you created in this lab. 123 | 124 | 2. On the resource page, select **Delete** and follow the instructions to delete the resource. Alternatively, you can delete the entire resource group to clean up all resources at the same time. 125 | 126 | ## More information 127 | 128 | For more information about containerizing Azure AI services, see the [Azure AI Services containers documentation](https://learn.microsoft.com/azure/ai-services/cognitive-services-container-support). 129 | -------------------------------------------------------------------------------- /Instructions/Exercises/05-implement-content-safety.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Implement Azure AI Content Safety' 4 | --- 5 | 6 | # Implement Azure AI Content Safety 7 | 8 | In this exercise, you will provision a Content Safety resource, test the resource in Azure AI Studio, and test the resource in code. 9 | 10 | ## Provision a *Content Safety* resource 11 | 12 | If you don't already have one, you'll need to provision a **Content Safety** resource in your Azure subscription. 13 | 14 | 1. Open the Azure portal at `https://portal.azure.com`, and sign in using the Microsoft account associated with your Azure subscription. 15 | 1. Select **Create a resource**. 16 | 1. In the search field, search for **Content Safety**. Then, in the results, select **Create** under **Azure AI Content Safety**. 17 | 1. Provision the resource using the following settings: 18 | - **Subscription**: *Your Azure subscription*. 19 | - **Resource group**: *Choose or create a resource group*. 20 | - **Region**: Select **East US** 21 | - **Name**: *Enter a unique name*. 22 | - **Pricing tier**: Select **F0** (*free*), or **S** (*standard*) if F0 is not available. 23 | 1. Select **Review + create**, then select **Create** to provision the resource. 24 | 1. Wait for deployment to complete, and then go to the resource. 25 | 1. Select **Access Control** in the left navigation bar, then select **+ Add** and **Add role assignment**. 26 | 1. Scroll down to choose the **Cognitive Services User** role and select **Next**. 27 | 1. Add your account to this role, and then select **Review + assign**. 28 | 1. Select **Resource Management** in the left hand navigation bar and select **Keys and Endpoint**. Leave this page open so you can copy the keys later. 29 | 30 | ## Use Azure AI Content Safety Prompt Shields 31 | 32 | In this exercise you will use Azure AI Studio to test Content Safety Prompt Shields with two sample inputs. One simulates a user prompt, and the other simulates a document with potentially unsafe text embedded into it. 33 | 34 | 1. In another browser tab, open the Content Safety page of [Azure AI Studio](https://ai.azure.com/explore/contentsafety) and sign in. 35 | 1. Under **Moderate text content** select **Try it out**. 36 | 1. On the **Moderate text content** page, under **Azure AI Services** select the Content Safety resource you created earlier. 37 | 1. Select **Multiple risk categories in one sentence**. Review the document text for potential issues. 38 | 1. Select **Run test** and review the results. 39 | 1. Optionally, alter the threshold levels and select **Run test** again. 40 | 1. On the left navigation bar, select **Protected material detection for text**. 41 | 1. Select **Protected lyrics** and note that these are the lyrics of a published song. 42 | 1. Select **Run test** and review the results. 43 | 1. On the left navigation bar, select **Moderate image content**. 44 | 1. Select **Self-harm content**. 45 | 1. Notice that all images are blurred by default in AI Studio. You should also be aware that the sexual content in the samples is very mild. 46 | 1. Select **Run test** and review the results. 47 | 1. On the left navigation bar, select **Prompt shields**. 48 | 1. On the **Prompt shields page**, under **Azure AI Services** select the Content Safety resource you created earlier. 49 | 1. Select **Prompt & document attack content**. Review the user prompt and document text for potential issues. 50 | 1. Select **Run test**. 51 | 1. In **View results**, verify that Jailbreak attacks were detected in both the user prompt and the document. 52 | 53 | > [!TIP] 54 | > Code is available for all of the samples in AI Studio. 55 | 56 | 1. Under **Next steps**, under **View the code** select **View code**. The **Sample code** window is displayed. 57 | 1. Use the down arrow to select either Python or C# and then select **Copy** to copy the sample code to the clipboard. 58 | 1. Close the **Sample code** screen. 59 | 60 | ### Configure your application 61 | 62 | You will now create an application in either C# or Python. 63 | 64 | #### C# 65 | 66 | ##### Prerequisites 67 | 68 | * [Visual Studio Code](https://code.visualstudio.com/) on one of the [supported platforms](https://code.visualstudio.com/docs/supporting/requirements#_platforms). 69 | * [.NET 8](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) is the target framework for this exercise. 70 | * The [C# extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) for Visual Studio Code. 71 | 72 | ##### Setting up 73 | 74 | Perform the following steps to prepare Visual Studio Code for the exercise. 75 | 76 | 1. Start Visual Studio Code and in the Explorer view, click **Create .NET Project** selecting **Console App**. 77 | 1. Select a folder on your computer, and give the project a name. Select **Create project** and acknowledge the warning message. 78 | 1. In the Explorer pane, expand Solution Explorer and select **Program.cs**. 79 | 1. Build and run the project by selecting **Run** -> **Run without Debugging**. 80 | 1. Under Solution Explorer, right-click the C# project and select **Add NuGet Package.** 81 | 1. Search for **Azure.AI.TextAnalytics** and select the latest version. 82 | 1. Search for a second NuGet Package: **Microsoft.Extensions.Configuration.Json 8.0.0**. The project file should now list two NuGet packages. 83 | 84 | ##### Add code 85 | 86 | 1. Paste the sample code you copied earlier under the **ItemGroup** section. 87 | 1. Scroll down to find *Replace with your own subscription _key and endpoint*. 88 | 1. In the Azure portal, on the Keys and Endpoint page, copy one of the Keys (1 or 2). Replace **** with this value. 89 | 1. In the Azure portal, on the Keys and Endpoint page, copy the Endpoint. Paste this value into your code to replace ****. 90 | 1. In **Azure AI Studio**, copy the **User prompt** value. Paste this into your code to replace ****. 91 | 1. Scroll down to **** and delete this line of code. 92 | 1. In **Azure AI Studio**, copy the **Document** value. 93 | 1. Scroll down to **** and paste your document value. 94 | 1. Select **Run** -> **Run without Debugging** and verify that an attack was detected. 95 | 96 | #### Python 97 | 98 | ##### Prerequisites 99 | 100 | * [Visual Studio Code](https://code.visualstudio.com/) on one of the [supported platforms](https://code.visualstudio.com/docs/supporting/requirements#_platforms). 101 | 102 | * The [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python) is installed for Visual Studio Code. 103 | 104 | * The [requests module](https://pypi.org/project/requests/) is installed. 105 | 106 | 1. Create a new Python file with a **.py** extension and give it a suitable name. 107 | 1. Paste the sample code you copied earlier. 108 | 1. Scroll down to find the section titled *Replace with your own subscription _key and endpoint*. 109 | 1. In the Azure portal, on the Keys and Endpoint page, copy one of the Keys (1 or 2). Replace **** with this value. 110 | 1. In the Azure portal, on the Keys and Endpoint page, copy the Endpoint. Paste this value into your code to replace ****. 111 | 1. In **Azure AI Studio**, copy the **User prompt** value. Paste this into your code to replace ****. 112 | 1. Scroll down to **** and delete this line of code. 113 | 1. In **Azure AI Studio**, copy the **Document** value. 114 | 1. Scroll down to **** and paste your document value. 115 | 1. From the integrated terminal for your file, run the program, eg: 116 | 117 | - `.\prompt-shield.py` 118 | 119 | 1. Validate that an attack is detected. 120 | 1. Optionally, you can experiment with different test content and document values. 121 | -------------------------------------------------------------------------------- /Instructions/Labs/01-use-azure-ai-services.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Get Started with Azure AI Services' 4 | description: 'Provision Azure AI Services for your application.' 5 | --- 6 | 7 | # Get Started with Azure AI Services 8 | 9 | In this exercise, you'll get started with Azure AI Services by creating an **Azure AI Services** resource in your Azure subscription and using it from a client application. The goal of the exercise is not to gain expertise in any particular service, but rather to become familiar with a general pattern for provisioning and working with Azure AI services as a developer. 10 | 11 | ## Provision an Azure AI Services resource 12 | 13 | Azure AI Services are cloud-based services that encapsulate artificial intelligence capabilities you can incorporate into your applications. You can provision individual Azure AI services resources for specific APIs (for example, **Language** or **Vision**), or you can provision a single **Azure AI Services** resource that provides access to multiple Azure AI services APIs through a single endpoint and key. In this case, you'll use a single **Azure AI Services** resource. 14 | 15 | 1. Open the Azure portal at `https://portal.azure.com`, and sign in using the Microsoft account associated with your Azure subscription. 16 | 2. In the top search bar, search for *Azure AI services*, select **Azure AI services multi-service account**, and create a resource with the following settings: 17 | - **Subscription**: *Your Azure subscription* 18 | - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* 19 | - **Region**: *Choose any available region* 20 | - **Name**: *Enter a unique name* 21 | - **Pricing tier**: Standard S0 22 | 3. Select the required checkboxes and create the resource. 23 | 4. Wait for deployment to complete, and then view the deployment details. 24 | 5. Go to the resource and view its **Keys and Endpoint** page. This page contains the information that you will need to connect to your resource and use it from applications you develop. Specifically: 25 | - An HTTP *endpoint* to which client applications can send requests. 26 | - Two *keys* that can be used for authentication (client applications can use either key to authenticate). 27 | - The *location* where the resource is hosted. This is required for requests to some (but not all) APIs. 28 | 29 | ## Clone the repository in Cloud Shell 30 | 31 | You'll develop your code using Cloud Shell from the Azure Portal. The code files for your app have been provided in a GitHub repo. 32 | 33 | > **Tip**: If you have already cloned the **mslearn-ai-services** repo recently, you can skip this task. Otherwise, follow these steps to clone it to your development environment. 34 | 35 | 1. In the Azure Portal, use the **[\>_]** button to the right of the search bar at the top of the page to create a new Cloud Shell in the Azure portal, selecting a ***PowerShell*** environment. The cloud shell provides a command line interface in a pane at the bottom of the Azure portal. 36 | 37 | > **Note**: If you have previously created a cloud shell that uses a *Bash* environment, switch it to ***PowerShell***. 38 | 39 | 1. In the cloud shell toolbar, in the **Settings** menu, select **Go to Classic version** (this is required to use the code editor). 40 | 41 | > **Tip**: As you paste commands into the cloudshell, the ouput may take up a large amount of the screen buffer. You can clear the screen by entering the `cls` command to make it easier to focus on each task. 42 | 43 | 1. In the PowerShell pane, enter the following commands to clone the GitHub repo for this exercise: 44 | 45 | ``` 46 | rm -r mslearn-ai-services -f 47 | git clone https://github.com/microsoftlearning/mslearn-ai-services mslearn-ai-services 48 | ``` 49 | 50 | 1. After the repo has been cloned, navigate to the folder containing the application code files: 51 | 52 | ``` 53 | cd mslearn-ai-services/Labfiles/01-use-azure-ai-services 54 | ``` 55 | 56 | ## Use a REST Interface 57 | 58 | The Azure AI services APIs are REST-based, so you can consume them by submitting JSON requests over HTTP. In this example, you'll explore a console application that uses the **Language** REST API to perform language detection; but the basic principle is the same for all of the APIs supported by the Azure AI Services resource. 59 | 60 | > **Note**: In this exercise, you can choose to use the REST API from either **C#** or **Python**. In the steps below, perform the actions appropriate for your preferred language. 61 | 62 | 1. Navigate to the folder containing the application code files for your preferred language: 63 | 64 | **Python** 65 | 66 | ``` 67 | cd Python/rest-client 68 | ``` 69 | 70 | **C#** 71 | 72 | ``` 73 | cd C-Sharp/rest-client 74 | ``` 75 | 76 | 1. Using the `ls` command, you can view the contents of the **rest-client** folder. Note that it contains a file for configuration settings: 77 | 78 | - **Python**: .env 79 | - **C#**: appsettings.json 80 | 81 | 1. Enter the following command to edit the configuration file that has been provided: 82 | 83 | **Python** 84 | 85 | ``` 86 | code .env 87 | ``` 88 | 89 | **C#** 90 | 91 | ``` 92 | code appsettings.json 93 | ``` 94 | 95 | The file is opened in a code editor. 96 | 97 | 1. In the code file, update the configuration values it contains to reflect the **endpoint** and an authentication **key** for your Azure AI services resource. 98 | 1. After you've replaced the placeholders, use the **CTRL+S** command to save your changes and then use the **CTRL+Q** command to close the code editor while keeping the cloud shell command line open. 99 | 1. Enter the following command to open the code file for the client application: 100 | 101 | **Python** 102 | 103 | ``` 104 | code rest-client.py 105 | ``` 106 | 107 | **C#** 108 | 109 | ``` 110 | code Program.cs 111 | ``` 112 | 113 | 1. Review the code it contains, noting the following details: 114 | - Various namespaces are imported to enable HTTP communication 115 | - Code in the **Main** function retrieves the endpoint and key for your Azure AI services resource - these will be used to send REST requests to the Text Analytics service. 116 | - The program accepts user input, and uses the **GetLanguage** function to call the Text Analytics language detection REST API for your Azure AI services endpoint to detect the language of the text that was entered. 117 | - The request sent to the API consists of a JSON object containing the input data - in this case, a collection of **document** objects, each of which has an **id** and **text**. 118 | - The key for your service is included in the request header to authenticate your client application. 119 | - The response from the service is a JSON object, which the client application can parse. 120 | 121 | 1. Use the **CTRL+Q** command to close the code editor while keeping the cloud shell command line open and run the following command: 122 | 123 | **Python** 124 | 125 | ``` 126 | pip install python-dotenv 127 | python rest-client.py 128 | ``` 129 | 130 | **C#** 131 | 132 | ``` 133 | dotnet run 134 | ``` 135 | 136 | 1. When prompted, enter some text and review the language that is detected by the service, which is returned in the JSON response. For example, try entering "Hello", "Bonjour", and "Gracias". 137 | 1. When you have finished testing the application, enter "quit" to stop the program. 138 | 139 | ## Use an SDK 140 | 141 | You can write code that consumes Azure AI services REST APIs directly, but there are software development kits (SDKs) for many popular programming languages, including Microsoft C#, Python, Java, and Node.js. Using an SDK can greatly simplify development of applications that consume Azure AI services. 142 | 143 | 1. Navigate to the folder containing the SDK application code files by running `cd ../sdk-client`. 144 | 145 | 1. Install the Text Analytics SDK package by running the appropriate command for your language preference: 146 | 147 | **Python** 148 | 149 | ``` 150 | pip install azure-ai-textanalytics==5.3.0 151 | ``` 152 | 153 | **C#** 154 | 155 | ``` 156 | dotnet add package Azure.AI.TextAnalytics --version 5.3.0 157 | ``` 158 | 159 | 1. Enter the following command to edit the configuration file that has been provided: 160 | 161 | **Python** 162 | 163 | ``` 164 | code .env 165 | ``` 166 | 167 | **C#** 168 | 169 | ``` 170 | code appsettings.json 171 | ``` 172 | 173 | 1. In the code file, update the configuration values it contains to reflect the **endpoint** and an authentication **key** for your Azure AI services resource. 174 | 1. After you've replaced the placeholders, use the **CTRL+S** command to save your changes and then use the **CTRL+Q** command to close the code editor while keeping the cloud shell command line open. 175 | 1. Enter the following command to open the code file for the client application: 176 | 177 | **Python** 178 | 179 | ``` 180 | code sdk-client.py 181 | ``` 182 | 183 | **C#** 184 | 185 | ``` 186 | code Program.cs 187 | ``` 188 | 189 | 1. Review the code it contains, noting the following details: 190 | - The namespace for the SDK you installed is imported 191 | - Code in the **Main** function retrieves the endpoint and key for your Azure AI services resource - these will be used with the SDK to create a client for the Text Analytics service. 192 | - The **GetLanguage** function uses the SDK to create a client for the service, and then uses the client to detect the language of the text that was entered. 193 | 194 | 1. Use the **CTRL+Q** command to close the code editor and run the following command: 195 | 196 | **Python** 197 | 198 | ``` 199 | python sdk-client.py 200 | ``` 201 | 202 | **C#** 203 | 204 | ``` 205 | dotnet run 206 | ``` 207 | 208 | 7. When prompted, enter some text and review the language that is detected by the service. For example, try entering "Goodbye", "Au revoir", and "Hasta la vista". 209 | 8. When you have finished testing the application, enter "quit" to stop the program. 210 | 211 | > **Note**: Some languages that require Unicode character sets may not be recognized in this simple console application. 212 | 213 | ## Clean up resources 214 | 215 | If you're not using the Azure resources created in this lab for other training modules, you can delete them to avoid incurring further charges. 216 | 217 | 1. Open the Azure portal at `https://portal.azure.com`, and in the top search bar, search for the resources you created in this lab. 218 | 219 | 2. On the resource page, select **Delete** and follow the instructions to delete the resource. Alternatively, you can delete the entire resource group to clean up all resources at the same time. 220 | 221 | ## More information 222 | 223 | For more information about Azure AI Services, see the [Azure AI Services documentation](https://docs.microsoft.com/azure/ai-services/what-are-ai-services). 224 | -------------------------------------------------------------------------------- /Instructions/Labs/02-ai-services-security.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Manage Azure AI Services Security' 4 | description: 'Manage and secure access to your Azure AI Services resource.' 5 | --- 6 | 7 | # Manage Azure AI Services Security 8 | 9 | Security is a critical consideration for any application, and as a developer you should ensure that access to resources such as Azure AI services is restricted to only those who require it. 10 | 11 | Access to Azure AI services is typically controlled through authentication keys, which are generated when you initially create an Azure AI services resource. 12 | 13 | ## Provision an Azure AI Services resource 14 | 15 | If you don't already have one in your subscription, you'll need to provision an **Azure AI Services** resource. 16 | 17 | 1. Open the Azure portal at `https://portal.azure.com`, and sign in using the Microsoft account associated with your Azure subscription. 18 | 2. In the top search bar, search for *Azure AI services*, select **Azure AI services multi-service account**, and create a resource with the following settings: 19 | - **Subscription**: *Your Azure subscription* 20 | - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* 21 | - **Region**: *Choose any available region* 22 | - **Name**: *Enter a unique name* 23 | - **Pricing tier**: Standard S0 24 | 3. Select the required checkboxes and create the resource. 25 | 4. Wait for deployment to complete, and then view the deployment details. 26 | 27 | ## Clone the repository in Cloud Shell 28 | 29 | You'll develop your code using Cloud Shell from the Azure Portal. The code files for your app have been provided in a GitHub repo. 30 | 31 | > **Tip**: If you have already cloned the **mslearn-ai-services** repo recently, you can skip this task. Otherwise, follow these steps to clone it to your development environment. 32 | 33 | 1. In the Azure Portal, use the **[\>_]** button to the right of the search bar at the top of the page to create a new Cloud Shell in the Azure portal, selecting a ***PowerShell*** environment. The cloud shell provides a command line interface in a pane at the bottom of the Azure portal. 34 | 35 | > **Note**: If you have previously created a cloud shell that uses a *Bash* environment, switch it to ***PowerShell***. 36 | 37 | 1. In the cloud shell toolbar, in the **Settings** menu, select **Go to Classic version** (this is required to use the code editor). 38 | 39 | > **Tip**: As you paste commands into the cloudshell, the ouput may take up a large amount of the screen buffer. You can clear the screen by entering the `cls` command to make it easier to focus on each task. 40 | 41 | 1. In the PowerShell pane, enter the following commands to clone the GitHub repo for this exercise: 42 | 43 | ``` 44 | rm -r mslearn-ai-services -f 45 | git clone https://github.com/microsoftlearning/mslearn-ai-services mslearn-ai-services 46 | ``` 47 | 48 | 1. After the repo has been cloned, navigate to the folder containing the application code files: 49 | 50 | ``` 51 | cd mslearn-ai-services/Labfiles/02-ai-services-security 52 | ``` 53 | 54 | ## Manage authentication keys 55 | 56 | When you created your Azure AI services resource, two authentication keys were generated. You can manage these in the Azure portal or by using the Azure command line interface (CLI). 57 | 58 | 1. Choose one method of obtaining your authentication keys and endpoint: 59 | 60 | **Using the Azure portal**: In the Azure portal, go to your Azure AI services resource and view its **Keys and Endpoint** page. This page contains the information that you will need to connect to your resource and use it from applications you develop. Specifically: 61 | - An HTTP *endpoint* to which client applications can send requests. 62 | - Two *keys* that can be used for authentication (client applications can use either of the keys. A common practice is to use one for development, and another for production. You can easily regenerate the development key after developers have finished their work to prevent continued access). 63 | - The *location* where the resource is hosted. This is required for requests to some (but not all) APIs. 64 | 65 | **Using the Command Line**: Alternatively you can use the following command to get the list of Azure AI services keys. In the Cloud Shell, paste in the following command; replacing *<resourceName>* with the name of your Azure AI services resource, and *<resourceGroup>* with the name of the resource group in which you created it. 66 | 67 | ``` 68 | az cognitiveservices account keys list --name --resource-group 69 | ``` 70 | 71 | The command returns a list of the keys for your Azure AI services resource - there are two keys, named **key1** and **key2**. 72 | 73 | > **Tip**: If you have authentication issues, first run `az login` and sign into your account. 74 | 75 | To test your Azure AI service, you can use **curl** - a command line tool for HTTP requests. 76 | 77 | 1. Run the **curl** command below, replacing *<yourEndpoint>* and *<yourKey>* with your endpoint URI and **Key1** key to use the Analyze Text API in your Azure AI services resource. 78 | 79 | ```bash 80 | curl -X POST "/language/:analyze-text?api-version=2023-04-01" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: " --data-ascii "{'analysisInput':{'documents':[{'id':1,'text':'hello'}]}, 'kind': 'LanguageDetection'}" 81 | ``` 82 | 83 | The command returns a JSON document containing information about the language detected in the input data (which should be English). 84 | 85 | 1. If a key becomes compromised, or the developers who have it no longer require access, you can regenerate it in the portal or by using the Azure CLI. Run the following command to regenerate your **key1** key (replacing *<resourceName>* and *<resourceGroup>* for your resource). 86 | 87 | ``` 88 | az cognitiveservices account keys regenerate --name --resource-group --key-name key1 89 | ``` 90 | 91 | The list of keys for your Azure AI services resource is returned - note that **key1** has changed since you last retrieved them. 92 | 93 | 6. Re-run the **curl** command with the old key (you can use the **^** arrow on your keyboard to cycle through previous commands), and verify that it now fails. 94 | 7. Edit the *curl* command replacing the key with the new **key1** value, and save the changes. Then rerun the **curl** command and verify that it succeeds. 95 | 96 | > **Tip**: In this exercise, you used the full names of Azure CLI parameters, such as **--resource-group**. You can also use shorter alternatives, such as **-g**, to make your commands less verbose (but a little harder to understand). The [Azure AI Services CLI command reference](https://docs.microsoft.com/cli/azure/cognitiveservices?view=azure-cli-latest) lists the parameter options for each Azure AI services CLI command. 97 | 98 | ## Secure key access with Azure Key Vault 99 | 100 | You can develop applications that consume Azure AI services by using a key for authentication. However, this means that the application code must be able to obtain the key. One option is to store the key in an environment variable or a configuration file where the application is deployed, but this approach leaves the key vulnerable to unauthorized access. A better approach when developing applications on Azure is to store the key securely in Azure Key Vault, and provide access to the key through a *managed identity* (in other words, a user account used by the application itself). 101 | 102 | ### Create a key vault and add a secret 103 | 104 | First, you need to create a key vault and add a *secret* for the Azure AI services key. 105 | 106 | 1. Make a note of the **key1** value for your Azure AI services resource (or copy it to the clipboard). 107 | 2. In the Azure portal, on the **Home** page, select the **+Create a resource** button, search for *Key Vault*, and create a **Key Vault** resource with the following settings: 108 | 109 | - **Basics** tab 110 | - **Subscription**: *Your Azure subscription* 111 | - **Resource group**: *The same resource group as your Azure AI service resource* 112 | - **Key vault name**: *Enter a unique name* 113 | - **Region**: *The same region as your Azure AI service resource* 114 | - **Pricing tier**: Standard 115 | 116 | - **Access configuration** tab 117 | - **Permission model**: Vault access policy 118 | - Scroll down to the **Access policies** section and select your user using the checkbox on the left. Then select **Review + create**, and select **Create** to create your resource. 119 | 120 | 3. Wait for deployment to complete and then go to your key vault resource. 121 | 4. In the left navigation pane, select **Secrets** (in the Objects section). 122 | 5. Select **+ Generate/Import** and add a new secret with the following settings : 123 | - **Upload options**: Manual 124 | - **Name**: `AI-Services-Key` *(it's important to match this exactly, because later you'll run code that retrieves the secret based on this name)* 125 | - **Secret value**: *Your **key1** Azure AI services key* 126 | 6. Select **Create**. 127 | 128 | ### Create a service principal 129 | 130 | To access the secret in the key vault, your application must use a service principal that has access to the secret. You'll use the Azure command line interface (CLI) to create the service principal, find its object ID, and grant access to the secret in Azure Vault. 131 | 132 | 1. Run the following Azure CLI command, replacing *<spName>* with a unique suitable name for an application identity (for example, *ai-app* with your initials appended on the end; the name must be unique within your tenant). Also replace *<subscriptionId>* and *<resourceGroup>* with the correct values for your subscription ID and the resource group containing your Azure AI services and key vault resources: 133 | 134 | > **Tip**: If you are unsure of your subscription ID, use the **az account show** command to retrieve your subscription information - the subscription ID is the **id** attribute in the output. If you see an error about the object already existing, please choose a different unique name. 135 | 136 | ``` 137 | az ad sp create-for-rbac -n "api://" 138 | ``` 139 | 140 | The output of this command includes information about your new service principal. It should look similar to this: 141 | 142 | ``` 143 | { 144 | "appId": "abcd12345efghi67890jklmn", 145 | "displayName": "api://ai-app-", 146 | "password": "1a2b3c4d5e6f7g8h9i0j", 147 | "tenant": "1234abcd5678fghi90jklm" 148 | } 149 | ``` 150 | 151 | Make a note of the **appId**, **password**, and **tenant** values - you will need them later (if you close this terminal, you won't be able to retrieve the password; so it's important to note the values now - you can paste the output into a new text file on your local machine to ensure you can find the values you need later!) 152 | 153 | 2. To get the **object ID** of your service principal, run the following Azure CLI command, replacing *<appId>* with the value of your service principal's app ID. 154 | 155 | ``` 156 | az ad sp show --id 157 | ``` 158 | 159 | 3. Copy the `id` value in the json returned in response. 160 | 3. To assign permission for your new service principal to access secrets in your Key Vault, run the following Azure CLI command, replacing *<keyVaultName>* with the name of your Azure Key Vault resource and *<objectId>* with the value of your service principal's ID value you've just copied. 161 | 162 | ``` 163 | az keyvault set-policy -n --object-id --secret-permissions get list 164 | ``` 165 | 166 | ### Use the service principal in an application 167 | 168 | Now you're ready to use the service principal identity in an application, so it can access the secret Azure AI services key in your key vault and use it to connect to your Azure AI services resource. 169 | 170 | > **Note**: In this exercise, we'll store the service principal credentials in the application configuration and use them to authenticate a **ClientSecretCredential** identity in your application code. This is fine for development and testing, but in a real production application, an administrator would assign a *managed identity* to the application so that it uses the service principal identity to access resources, without caching or storing the password. 171 | 172 | 1. In your terminal, switch to the **C-Sharp** or **Python** folder depending on your language preference by running `cd C-Sharp` or `cd Python`. Then run `cd keyvault_client` to navigate to the app folder. 173 | 2. Install the packages you will need to use for Azure Key Vault and the Text Analytics API in your Azure AI services resource by running the appropriate command for your language preference: 174 | 175 | **C#** 176 | 177 | ``` 178 | dotnet add package Azure.AI.TextAnalytics --version 5.3.0 179 | dotnet add package Azure.Identity --version 1.12.0 180 | dotnet add package Azure.Security.KeyVault.Secrets --version 4.6.0 181 | ``` 182 | 183 | **Python** 184 | 185 | ``` 186 | python -m venv labenv 187 | ./labenv/bin/Activate.ps1 188 | pip install python-dotenv azure-identity==1.17.1 azure-keyvault-secrets==4.8.0 azure-ai-textanalytics==5.3.0 189 | ``` 190 | 191 | 3. Run the `ls` command to view the contents of the **keyvault-client** folder, and note that it contains a file for configuration settings: 192 | - **C#**: appsettings.json 193 | - **Python**: .env 194 | 195 | Open the configuration file by running `code appsettings.json` or `code .env` and update the configuration values it contains to reflect the following settings: 196 | 197 | - The **endpoint** for your Azure AI Services resource 198 | - The name of your **Azure Key Vault** resource 199 | - The **tenant** for your service principal 200 | - The **appId** for your service principal 201 | - The **password** for your service principal 202 | 203 | Save your changes by pressing **CTRL+S** and close the code editor by pressing **CTRL+Q**. 204 | 205 | 4. Note that the **keyvault-client** folder contains a code file for the client application: 206 | 207 | - **C#**: Program.cs 208 | - **Python**: keyvault-client.py 209 | 210 | Open the code file and review the code it contains, noting the following details: 211 | - The namespace for the SDK you installed is imported 212 | - Code in the **Main** function retrieves the application configuration settings, and then it uses the service principal credentials to get the Azure AI services key from the key vault. 213 | - The **GetLanguage** function uses the SDK to create a client for the service, and then uses the client to detect the language of the text that was entered. 214 | 5. Close the code editor and enter the following command to run the program: 215 | 216 | **C#** 217 | 218 | ``` 219 | dotnet run 220 | ``` 221 | 222 | **Python** 223 | 224 | ``` 225 | python keyvault-client.py 226 | ``` 227 | 228 | 7. When prompted, enter some text and review the language that is detected by the service. For example, try entering "Hello", "Bonjour", and "Gracias". 229 | 8. When you have finished testing the application, enter "quit" to stop the program. 230 | 231 | ## Clean up resources 232 | 233 | If you're not using the Azure resources created in this lab for other training modules, you can delete them to avoid incurring further charges. 234 | 235 | 1. Open the Azure portal at `https://portal.azure.com`, and in the top search bar, search for the resources you created in this lab. 236 | 237 | 2. On the resource page, select **Delete** and follow the instructions to delete the resource. Alternatively, you can delete the entire resource group to clean up all resources at the same time. 238 | 239 | ## More information 240 | 241 | For more information about securing Azure AI services, see the [Azure AI Services security documentation](https://docs.microsoft.com/azure/ai-services/security-features). 242 | -------------------------------------------------------------------------------- /Instructions/Labs/03-monitor-ai-services.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Monitor Azure AI Services' 4 | description: 'Monitor Azure AI Services usage and set up alerts.' 5 | --- 6 | 7 | # Monitor Azure AI Services 8 | 9 | Azure AI Services can be a critical part of an overall application infrastructure. It's important to be able to monitor activity and get alerted to issues that may need attention. 10 | 11 | ## Provision an Azure AI Services resource 12 | 13 | If you don't already have one in your subscription, you'll need to provision an **Azure AI Services** resource. 14 | 15 | 1. Open the Azure portal at `https://portal.azure.com`, and sign in using the Microsoft account associated with your Azure subscription. 16 | 2. In the top search bar, search for *Azure AI services*, select **Azure AI services multi-service account**, and create a resource with the following settings: 17 | - **Subscription**: *Your Azure subscription* 18 | - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* 19 | - **Region**: *Choose any available region* 20 | - **Name**: *Enter a unique name* 21 | - **Pricing tier**: Standard S0 22 | 3. Select any required checkboxes and create the resource. 23 | 4. Wait for deployment to complete, and then view the deployment details. 24 | 5. When the resource has been deployed, go to it and view its **Keys and Endpoint** page. Make a note of the endpoint URI - you will need it later. 25 | 26 | ## Configure an alert 27 | 28 | Let's start monitoring by defining an alert rule so you can detect activity in your Azure AI services resource. 29 | 30 | 1. In the Azure portal, go to your Azure AI services resource and view its **Alerts** page (in the **Monitoring** section). 31 | 2. Select **+ Create** dropdown, and select **Alert rule** 32 | 3. In the **Create an alert rule** page, under **Scope**, verify that the your Azure AI services resource is listed. (Close **Select a signal** pane if open) 33 | 4. Select **Condition** tab, and select on the **See all signals** link to show the **Select a signal** pane that appears on the right, where you can select a signal type to monitor. 34 | 5. In the **Signal type** list, scroll down to the **Activity Log** section, and then select **List Keys (Cognitive Services API Account)**. Then select **Apply**. 35 | 6. Review the activity over the past 6 hours. 36 | 7. Select the **Actions** tab. Note that you can specify an *action group*. This enables you to configure automated actions when an alert is fired - for example, sending an email notification. We won't do that in this exercise; but it can be useful to do this in a production environment. 37 | 8. In the **Details** tab, set the **Alert rule name** to **Key List Alert**. 38 | 9. Select **Review + create**. 39 | 10. Review the configuration for the alert. Select **Create** and wait for the alert rule to be created. 40 | 11. In the Azure Portal, use the **[\>_]** button to the right of the search bar at the top of the page to create a new Cloud Shell in the Azure portal, selecting a ***PowerShell*** environment. The cloud shell provides a command line interface in a pane at the bottom of the Azure portal. 41 | 42 | > **Note**: If you have previously created a cloud shell that uses a *Bash* environment, switch it to ***PowerShell***. 43 | 44 | 12. Now you can use the following command to get the list of Azure AI services keys, replacing *<resourceName>* with the name of your Azure AI services resource, and *<resourceGroup>* with the name of the resource group in which you created it. 45 | 46 | ``` 47 | az cognitiveservices account keys list --name --resource-group 48 | ``` 49 | 50 | The command returns a list of the keys for your Azure AI services resource. 51 | 52 | > **Note** If you have authentication issues when using az commands, you may need to run `az login` before the list keys command will work. 53 | 54 | 13. Refresh your **Alerts page**. You should see a **Sev 4** alert listed in the table (if not, wait up to five minutes and refresh again). 55 | 14. Select the alert to see its details. 56 | 57 | ## Visualize a metric 58 | 59 | As well as defining alerts, you can view metrics for your Azure AI services resource to monitor its utilization. 60 | 61 | 1. In the Azure portal, in the page for your Azure AI services resource, select **Metrics** (in the **Monitoring** section). 62 | 1. If there is no existing chart, select **+ New chart**. Then in the **Metric** list, review the possible metrics you can visualize and select **Total Calls**. 63 | 1. In the **Aggregation** list, select **Count**. This will enable you to monitor the total calls to you Azure AI Service resource; which is useful in determining how much the service is being used over a period of time. 64 | 1. To generate some requests to your Azure AI service, you will use **curl** - a command line tool for HTTP requests. Run the command shown below, replacing *<yourEndpoint>* and *<yourKey>* with your endpoint URI and **Key1** key to use the Text Analytics API in your Azure AI services resource. 65 | 66 | ``` 67 | curl -X POST "/language/:analyze-text?api-version=2023-04-01" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: " --data-ascii "{'analysisInput':{'documents':[{'id':1,'text':'hello'}]}, 'kind': 'LanguageDetection'}" 68 | ``` 69 | 70 | The command returns a JSON document containing information about the language detected in the input data (which should be English). 71 | 72 | 1. Re-run the **curl** command multiple times to generate some call activity (you can use the **^** key to cycle through previous commands). 73 | 1. Return to the **Metrics** page in the Azure portal and refresh the **Total Calls** count chart. It may take a few minutes for the calls you made using *curl* to be reflected in the chart - keep refreshing the chart until it updates to include them. 74 | 75 | ## Clean up resources 76 | 77 | If you're not using the Azure resources created in this lab for other training modules, you can delete them to avoid incurring further charges. 78 | 79 | 1. Open the Azure portal at `https://portal.azure.com`, and in the top search bar, search for the resources you created in this lab. 80 | 81 | 2. On the resource page, select **Delete** and follow the instructions to delete the resource. Alternatively, you can delete the entire resource group to clean up all resources at the same time. 82 | 83 | ## More information 84 | 85 | One of the options for monitoring Azure AI services is to use *diagnostic logging*. Once enabled, diagnostic logging captures rich information about your Azure AI services resource usage, and can be a useful monitoring and debugging tool. It can take over an hour after setting up diagnostic logging to generate any information, which is why we haven't explored it in this exercise; but you can learn more about it in the [Azure AI Services documentation](https://docs.microsoft.com/azure/ai-services/diagnostic-logging). 86 | -------------------------------------------------------------------------------- /Instructions/Labs/04-use-a-container.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Use an Azure AI Services Container' 4 | description: 'Deploy your own container and use Azure AI Services within it.' 5 | --- 6 | 7 | # Use an Azure AI Services Container 8 | 9 | Using Azure AI services hosted in Azure enables application developers to focus on the infrastructure for their own code while benefiting from scalable services that are managed by Microsoft. However, in many scenarios, organizations require more control over their service infrastructure and the data that is passed between services. 10 | 11 | Many of the Azure AI services APIs can be packaged and deployed in a *container*, enabling organizations to host Azure AI services in their own infrastructure; for example in local Docker servers, Azure Container Instances, or Azure Kubernetes Services clusters. Containerized Azure AI services need to communicate with an Azure-based Azure AI services account to support billing; but application data is not passed to the back-end service, and organizations have greater control over the deployment configuration of their containers, enabling custom solutions for authentication, scalability, and other considerations. 12 | 13 | > **Note**: There is an issue currently being investigated that some users hit where containers won't deploy properly, and calls to those containers fail. Updates to this lab will be made as soon as the issue has been resolved. 14 | 15 | ## Provision an Azure AI Services resource 16 | 17 | If you don't already have one in your subscription, you'll need to provision an **Azure AI Services** resource. 18 | 19 | 1. Open the Azure portal at `https://portal.azure.com`, and sign in using the Microsoft account associated with your Azure subscription. 20 | 2. In the top search bar, search for *Azure AI services*, select **Azure AI services multi-service account**, and create a resource with the following settings: 21 | - **Subscription**: *Your Azure subscription* 22 | - **Resource group**: *Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group - use the one provided)* 23 | - **Region**: *Choose any available region* 24 | - **Name**: *Enter a unique name* 25 | - **Pricing tier**: Standard S0 26 | 3. Select the required checkboxes and create the resource. 27 | 4. Wait for deployment to complete, and then view the deployment details. 28 | 5. When the resource has been deployed, go to it and view its **Keys and Endpoint** page. You will need the endpoint and one of the keys from this page in the next procedure. 29 | 30 | ## Deploy and run a Sentiment Analysis container 31 | 32 | Many commonly used Azure AI services APIs are available in container images. For a full list, check out the [Azure AI services documentation](https://learn.microsoft.com/en-us/azure/ai-services/cognitive-services-container-support#containers-in-azure-ai-services). In this exercise, you'll use the container image for the Text Analytics *Sentiment analysis* API; but the principles are the same for all of the available images. 33 | 34 | 1. In the Azure portal, on the **Home** page, select the **+Create a resource** button, search for *container instances*, and create a **Container Instances** resource with the following settings: 35 | 36 | - **Basics**: 37 | - **Subscription**: *Your Azure subscription* 38 | - **Resource group**: *Choose the resource group containing your Azure AI services resource* 39 | - **Container name**: *Enter a unique name* 40 | - **Region**: *Choose any available region* 41 | - **Availability zones**: None 42 | - **SKU**: Standard 43 | - **Image source**: Other Registry 44 | - **Image type**: Public 45 | - **Image**: `mcr.microsoft.com/azure-cognitive-services/textanalytics/sentiment:latest` 46 | - **OS type**: Linux 47 | - **Size**: 1 vcpu, 8 GB memory 48 | - **Networking**: 49 | - **Networking type**: Public 50 | - **DNS name label**: *Enter a unique name for the container endpoint* 51 | - **Ports**: *Change the TCP port from 80 to **5000*** 52 | - **Advanced**: 53 | - **Restart policy**: On failure 54 | - **Environment variables**: 55 | 56 | | Mark as secure | Key | Value | 57 | | -------------- | --- | ----- | 58 | | Yes | `ApiKey` | *Either key for your Azure AI services resource* | 59 | | Yes | `Billing` | *The endpoint URI for your Azure AI services resource* | 60 | | No | `Eula` | `accept` | 61 | 62 | - **Command override**: [ ] 63 | - **Key management**: Microsoft-managed keys (MMK) 64 | - **Tags**: 65 | - *Don't add any tags* 66 | 67 | 2. Select **Review + create** then select **Create**. Wait for deployment to complete, and then go to the deployed resource. 68 | > **Note** Please note that deploying an Azure AI container to Azure Container Instances typically takes 5-10 minutes (provisioning) before they are ready to use. 69 | 3. Observe the following properties of your container instance resource on its **Overview** page: 70 | - **Status**: This should be *Running*. 71 | - **IP Address**: This is the public IP address you can use to access your container instances. 72 | - **FQDN**: This is the *fully-qualified domain name* of the container instances resource, you can use this to access the container instances instead of the IP address. 73 | 74 | > **Note**: In this exercise, you've deployed the Azure AI services container image for sentiment analysis to an Azure Container Instances (ACI) resource. You can use a similar approach to deploy it to a *[Docker](https://www.docker.com/products/docker-desktop)* host on your own computer or network by running the following command (on a single line) to deploy the sentiment analysis container to your local Docker instance, replacing *<yourEndpoint>* and *<yourKey>* with your endpoint URI and either of the keys for your Azure AI services resource. 75 | > The command will look for the image on your local machine, and if it doesn't find it there it will pull it from the *mcr.microsoft.com* image registry and deploy it to your Docker instance. When deployment is complete, the container will start and listen for incoming requests on port 5000. 76 | 77 | ``` 78 | docker run --rm -it -p 5000:5000 --memory 8g --cpus 1 mcr.microsoft.com/azure-cognitive-services/textanalytics/sentiment:latest Eula=accept Billing= ApiKey= 79 | ``` 80 | 81 | ## Use the container 82 | 83 | 1. In the Azure Portal, use the **[\>_]** button to the right of the search bar at the top of the page to create a new Cloud Shell in the Azure portal, selecting a ***PowerShell*** environment. The cloud shell provides a command line interface in a pane at the bottom of the Azure portal. 84 | 85 | > **Note**: If you have previously created a cloud shell that uses a *Bash* environment, switch it to ***PowerShell***. 86 | 87 | 1. Run the following **curl** command, replacing *<your_ACI_IP_address_or_FQDN>* with the IP address or FQDN for your container. 88 | 89 | ``` 90 | curl -X POST "http://:5000/text/analytics/v3.1/sentiment" -H "Content-Type: application/json" --data-ascii "{'documents':[{'id':1,'text':'The performance was amazing! The sound could have been clearer.'},{'id':2,'text':'The food and service were unacceptable. While the host was nice, the waiter was rude and food was cold.'}]}" 91 | ``` 92 | 93 | Note that you do not need to specify the Azure AI services endpoint or key - the request is processed by the containerized service. The container in turn communicates periodically with the service in Azure to report usage for billing, but does not send request data. 94 | 95 | 1. Verify that the command returns a JSON document containing information about the sentiment detected in the two input documents (which should be positive and negative, in that order). 96 | 97 | ## Troubleshooting 98 | 99 | > **Note:** 100 | > Seeing your container as "Running" in the Azure Portal does **not** always mean it is ready to process requests. If you try to use `curl` and get errors like: 101 | > 102 | > ```text 103 | > curl: (52) Empty reply from server 104 | > curl: (56) Recv failure: Connection reset by peer 105 | > ``` 106 | > 107 | > This may mean the container has not been started with the correct parameters or environment, or is missing model files or internet access for model download. 108 | 109 | ### Alternative: Deploying the Container using Azure CLI 110 | 111 | You can try the following command (replace the `rg-name`, `container-name`, `ApiKey` and `Billing` endpoint with your values): 112 | 113 | ```bash 114 | az container create \ 115 | --resource-group \ 116 | --name \ 117 | --image mcr.microsoft.com/azure-cognitive-services/sentiment \ 118 | --ports 5000 \ 119 | --dns-name-label ai102sentimentdemo \ 120 | --environment-variables Eula=accept \ 121 | --secure-environment-variables ApiKey= Billing= \ 122 | --cpu 2 --memory 4 \ 123 | --os-type Linux 124 | ``` 125 | After deployment, you can test the endpoint (replace as appropriate): 126 | ```bash 127 | curl -X POST "http://:5000/text/analytics/v3.0/sentiment?model-version=latest" \ 128 | -H "Content-Type: application/json" \ 129 | -d '{ 130 | "documents": [ 131 | { 132 | "id": "1-en", 133 | "language": "en", 134 | "text": "The performance was amazing! The sound could have been clearer." 135 | }, 136 | { 137 | "id": "2-en", 138 | "language": "en", 139 | "text": "The food and service were unacceptable. While the host was nice, the waiter was rude and food was cold." 140 | } 141 | ] 142 | }' 143 | ``` 144 | **Try it**: 145 | 146 | If v3.1 endpoints do not work, try using v3.0 or v3.1-preview.1 with above cmd. 147 | 148 | Always check the /status endpoint and container logs for model loading messages (look for: Model loaded from /input/TextAnalytics/v3.x/Sentiment). 149 | 150 | If you still encounter issues, running the container locally with Docker may help to diagnose local vs. cloud issues. 151 | 152 | ## Clean Up 153 | 154 | If you've finished experimenting with your container instance, you should delete it. 155 | 156 | 1. In the Azure portal, open the resource group where you created your resources for this exercise. 157 | 2. Select the container instance resource and delete it. 158 | 159 | ## Clean up resources 160 | 161 | If you're not using the Azure resources created in this lab for other training modules, you can delete them to avoid incurring further charges. 162 | 163 | 1. Open the Azure portal at `https://portal.azure.com`, and in the top search bar, search for the resources you created in this lab. 164 | 165 | 2. On the resource page, select **Delete** and follow the instructions to delete the resource. Alternatively, you can delete the entire resource group to clean up all resources at the same time. 166 | 167 | ## More information 168 | 169 | For more information about containerizing Azure AI services, see the [Azure AI Services containers documentation](https://learn.microsoft.com/azure/ai-services/cognitive-services-container-support). 170 | -------------------------------------------------------------------------------- /Instructions/Labs/05-implement-content-safety.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Implement Azure AI Content Safety' 4 | description: 'Provision a Content Safety resource to secure your application against harmful content.' 5 | --- 6 | 7 | # Implement Azure AI Content Safety 8 | 9 | In this exercise, you will provision a Content Safety resource, test the resource in Azure AI Foundry, and test the resource in code. 10 | 11 | ## Provision a *Content Safety* resource 12 | 13 | If you don't already have one, you'll need to provision a **Content Safety** resource in your Azure subscription. 14 | 15 | 1. Open the Azure portal at `https://portal.azure.com`, and sign in using the Microsoft account associated with your Azure subscription. 16 | 1. Select **Create a resource**. 17 | 1. In the search field, search for **Content Safety**. Then, in the results, select **Create** under **Azure AI Content Safety**. 18 | 1. Provision the resource using the following settings: 19 | - **Subscription**: *Your Azure subscription*. 20 | - **Resource group**: *Choose or create a resource group*. 21 | - **Region**: Select **East US** 22 | - **Name**: *Enter a unique name*. 23 | - **Pricing tier**: Select **F0** (*free*), or **S** (*standard*) if F0 is not available. 24 | 1. Select **Review + create**, then select **Create** to provision the resource. 25 | 1. Wait for deployment to complete, and then go to the resource. 26 | 1. Select **Access Control** in the left navigation bar, then select **+ Add** and **Add role assignment**. 27 | 1. Scroll down to choose the **Cognitive Services User** role and select **Next**. 28 | 1. Add your account to this role, and then select **Review + assign**. 29 | 1. Select **Resource Management** in the left hand navigation bar and select **Keys and Endpoint**. Leave this page open so you can copy the keys later. 30 | 31 | ## Use Azure AI Content Safety Prompt Shields 32 | 33 | In this exercise you will use Azure AI Foundry to test Content Safety Prompt Shields with two sample inputs. One simulates a user prompt, and the other simulates a document with potentially unsafe text embedded into it. 34 | 35 | 1. In another browser tab, open the Content Safety page of [Azure AI Foundry](https://ai.azure.com/explore/contentsafety) and sign in. 36 | 1. Under **Moderate text content** select **Try it out**. 37 | 1. On the **Moderate text content** page, under **Azure AI Services** select the Content Safety resource you created earlier. 38 | 1. Select **Multiple risk categories in one sentence**. Review the document text for potential issues. 39 | 1. Select **Run test** and review the results. 40 | 1. Optionally, alter the threshold levels and select **Run test** again. 41 | 1. On the **Moderate text content** drop-down menu at the top of the page, select **Protected material detection for text**. 42 | 1. Select **Protected lyrics** and note that these are the lyrics of a published song. 43 | 1. Select **Run test** and review the results. 44 | 1. On the **Protected material detection for text** drop-down menu at the top of the page, select **Moderate image content**. 45 | 1. Select **Self-harm content**. 46 | 1. Notice that all images are blurred by default in AI Foundry. You should also be aware that the sexual content in the samples is very mild. 47 | 1. Select **Run test** and review the results. 48 | 1. On the **Moderate image content** drop-down menu at the top of the page, select **Prompt shields**. 49 | 1. On the **Prompt shields page**, under **Azure AI Services** select the Content Safety resource you created earlier. 50 | 1. Select **Prompt & document attack content**. Review the user prompt and document text for potential issues. 51 | 1. Select **Run test**. 52 | 1. In **View results**, verify that Jailbreak attacks were detected in both the user prompt and the document. 53 | 54 | > [!TIP] 55 | > Code is available for all of the samples in AI Foundry. 56 | 57 | 1. Under **Next steps**, under **View the code** select **View code**. The **Sample code** window is displayed. 58 | 1. Use the down arrow to select either Python or C# and then select **Copy** to copy the sample code to the clipboard. 59 | 1. Close the **Sample code** screen. 60 | 61 | ## Clone the repository in Cloud Shell 62 | 63 | You'll develop your code using Cloud Shell from the Azure Portal. The code files for your app have been provided in a GitHub repo. 64 | 65 | > **Tip**: If you have already cloned the **mslearn-ai-services** repo recently, you can skip this task. Otherwise, follow these steps to clone it to your development environment. 66 | 67 | 1. In the Azure Portal, use the **[\>_]** button to the right of the search bar at the top of the page to create a new Cloud Shell in the Azure portal, selecting a ***PowerShell*** environment. The cloud shell provides a command line interface in a pane at the bottom of the Azure portal. 68 | 69 | > **Note**: If you have previously created a cloud shell that uses a *Bash* environment, switch it to ***PowerShell***. 70 | 71 | 1. In the cloud shell toolbar, in the **Settings** menu, select **Go to Classic version** (this is required to use the code editor). 72 | 73 | > **Tip**: As you paste commands into the cloudshell, the ouput may take up a large amount of the screen buffer. You can clear the screen by entering the `cls` command to make it easier to focus on each task. 74 | 75 | 1. In the PowerShell pane, enter the following commands to clone the GitHub repo for this exercise: 76 | 77 | ``` 78 | rm -r mslearn-ai-services -f 79 | git clone https://github.com/microsoftlearning/mslearn-ai-services mslearn-ai-services 80 | ``` 81 | 82 | 1. After the repo has been cloned, navigate to the language-specific folder containing the application code files, based on the programming language of your choice (Python or C#): 83 | 84 | **Python** 85 | 86 | ``` 87 | cd mslearn-ai-services/Labfiles/05-implement-content-safety/Python 88 | ``` 89 | 90 | **C#** 91 | 92 | ``` 93 | cd mslearn-ai-services/Labfiles/05-implement-content-safety/C-Sharp 94 | ``` 95 | 96 | 1. If you chose Python, enter the following command to install the library you'll use: 97 | 98 | **Python** 99 | 100 | ``` 101 | python -m venv labenv 102 | ./labenv/bin/Activate.ps1 103 | pip install requests 104 | ``` 105 | 106 | 1. Next, enter the following command to edit the application file that has been provided: 107 | 108 | **Python** 109 | 110 | ``` 111 | code prompt-shield-py 112 | ``` 113 | 114 | **C#** 115 | 116 | ``` 117 | code Program.cs 118 | ``` 119 | 120 | The file is opened in a code editor. 121 | 122 | 1. Scroll down to find *Replace with your own subscription _key and endpoint*. 123 | 1. In the Azure portal, on the Keys and Endpoint page, copy one of the Keys (1 or 2). Replace **** with this value. 124 | 1. In the Azure portal, on the Keys and Endpoint page, copy the Endpoint. Paste this value into your code to replace ****. 125 | 1. In **Azure AI Foundry**, copy the **User prompt** value. Paste this into your code to replace **** (Python) or **** (C#). 126 | 1. Scroll down to **** and delete this line of code. 127 | 1. In **Azure AI Foundry**, copy the **Document** value. 128 | 1. Scroll down to **** and paste your document value. 129 | 1. After you've replaced the placeholders, use the **CTRL+S** command to save your changes and then use the **CTRL+Q** command to close the code editor while keeping the cloud shell command line open. 130 | 1. Run the program and verify that an attack was detected: 131 | 132 | **Python** 133 | 134 | ``` 135 | python prompt-shield-py 136 | ``` 137 | 138 | **C#** 139 | 140 | ``` 141 | dotnet run 142 | ``` 143 | 144 | 1. Optionally, you can experiment with different test content and document values. 145 | 146 | ## Clean up resources 147 | 148 | If you're not using the Azure resources created in this lab for other training modules, you can delete them to avoid incurring further charges. 149 | 150 | 1. Open the Azure portal at `https://portal.azure.com`, and in the top search bar, search for the resources you created in this lab. 151 | 152 | 2. On the resource page, select **Delete** and follow the instructions to delete the resource. Alternatively, you can delete the entire resource group to clean up all resources at the same time. 153 | 154 | -------------------------------------------------------------------------------- /Instructions/media/ai-personalizer/7-chart2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicrosoftLearning/mslearn-ai-services/06023ca8fd67552a097666162ef613fd98efae33/Instructions/media/ai-personalizer/7-chart2.png -------------------------------------------------------------------------------- /Instructions/media/ai-personalizer/7-evaluation-form.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicrosoftLearning/mslearn-ai-services/06023ca8fd67552a097666162ef613fd98efae33/Instructions/media/ai-personalizer/7-evaluation-form.png -------------------------------------------------------------------------------- /Instructions/media/ai-personalizer/7-offline-eval-result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicrosoftLearning/mslearn-ai-services/06023ca8fd67552a097666162ef613fd98efae33/Instructions/media/ai-personalizer/7-offline-eval-result.png -------------------------------------------------------------------------------- /Instructions/media/ai-personalizer/8-create-metric-chart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicrosoftLearning/mslearn-ai-services/06023ca8fd67552a097666162ef613fd98efae33/Instructions/media/ai-personalizer/8-create-metric-chart.png -------------------------------------------------------------------------------- /Instructions/media/ai-personalizer/8-install-enable-extensions-code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicrosoftLearning/mslearn-ai-services/06023ca8fd67552a097666162ef613fd98efae33/Instructions/media/ai-personalizer/8-install-enable-extensions-code.png -------------------------------------------------------------------------------- /Instructions/media/ai-personalizer/8-press-run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicrosoftLearning/mslearn-ai-services/06023ca8fd67552a097666162ef613fd98efae33/Instructions/media/ai-personalizer/8-press-run.png -------------------------------------------------------------------------------- /Instructions/media/ai-personalizer/copy-key-endpoint.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicrosoftLearning/mslearn-ai-services/06023ca8fd67552a097666162ef613fd98efae33/Instructions/media/ai-personalizer/copy-key-endpoint.png -------------------------------------------------------------------------------- /Instructions/media/ai-personalizer/create-personalizer-portal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicrosoftLearning/mslearn-ai-services/06023ca8fd67552a097666162ef613fd98efae33/Instructions/media/ai-personalizer/create-personalizer-portal.png -------------------------------------------------------------------------------- /Instructions/media/cloudshell-launch-portal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicrosoftLearning/mslearn-ai-services/06023ca8fd67552a097666162ef613fd98efae33/Instructions/media/cloudshell-launch-portal.png -------------------------------------------------------------------------------- /Instructions/setup.md: -------------------------------------------------------------------------------- 1 | --- 2 | lab: 3 | title: 'Lab Environment Setup' 4 | module: 'Setup' 5 | --- 6 | 7 | # Lab Environment Setup 8 | 9 | Exercises are intended to be completed in a hosted lab environment. If you want to complete them on your own computer, you can do so by installing the following software. You may experience unexpected dialogs and behavior when using your own environment. Due to the wide range of possible local configurations, the course team cannot support issues you may encounter in your own environment. 10 | 11 | > **Note**: The instructions below are for a Windows 11 computer. You can also use Linux or MacOS. You may need to adapt the lab instructions for your chosen OS. 12 | 13 | ### Base Operating System (Windows 11) 14 | 15 | #### Windows 11 16 | 17 | Install Windows 11 and apply all updates. 18 | 19 | #### Edge 20 | 21 | Install [Edge (Chromium)](https://microsoft.com/edge) 22 | 23 | ### .NET Core SDK 24 | 25 | 1. Download and install from https://dotnet.microsoft.com/download (download .NET Core SDK - not just the runtime). If you are running the labs in this course on your own machine, you should have .NET 8.0. 26 | 27 | ### C++ Redistributable 28 | 29 | 1. Download and install the Visual C++ Redistributable (x64) from https://aka.ms/vs/16/release/vc_redist.x64.exe. 30 | 31 | ### Node.JS 32 | 33 | 1. Download the latest LTS version from https://nodejs.org/en/download/ 34 | 2. Install using the default options 35 | 36 | ### Python (and required packages) 37 | 38 | 1. Download version 3.11 from https://docs.conda.io/en/latest/miniconda.html 39 | 2. Run setup to install - **Important**: Select the options to add Miniconda to the PATH variable and to register Miniconda as the default Python environment. 40 | 3. After installation, open the Anaconda prompt and enter the following commands to install packages: 41 | 42 | ``` 43 | pip install flask requests python-dotenv pylint matplotlib pillow 44 | pip install --upgrade numpy 45 | ``` 46 | 47 | ### Azure CLI 48 | 49 | 1. Download from https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest 50 | 2. Install using the default options 51 | 52 | ### Git 53 | 54 | 1. Download and install from https://git-scm.com/download.html, using the default options 55 | 56 | 57 | ### Visual Studio Code (and extensions) 58 | 59 | 1. Download from https://code.visualstudio.com/Download 60 | 2. Install using the default options 61 | 3. After installation, start Visual Studio Code and on the **Extensions** tab (CTRL+SHIFT+X), search for and install the following extensions from Microsoft: 62 | - Python 63 | - C# 64 | - Azure Functions 65 | - PowerShell 66 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Microsoft Learning 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/C-Sharp/readme.txt: -------------------------------------------------------------------------------- 1 | This folder contains C# code -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/C-Sharp/rest-client/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Newtonsoft.Json.Linq; 3 | using System.Text; 4 | using System.Net.Http; 5 | using System.Net.Http.Headers; 6 | using System.Web; 7 | using Microsoft.Extensions.Configuration; 8 | using System.Threading.Tasks; 9 | 10 | namespace rest_client 11 | { 12 | class Program 13 | { 14 | private static string AiSvcEndpoint; 15 | private static string AiSvCKey; 16 | static async Task Main(string[] args) 17 | { 18 | try 19 | { 20 | // Get config settings from AppSettings 21 | IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); 22 | IConfigurationRoot configuration = builder.Build(); 23 | AiSvcEndpoint = configuration["AIServicesEndpoint"]; 24 | AiSvCKey = configuration["AIServicesKey"]; 25 | 26 | 27 | // Get user input (until they enter "quit") 28 | string userText = ""; 29 | while (userText.ToLower() != "quit") 30 | { 31 | Console.WriteLine("Enter some text ('quit' to stop)"); 32 | userText = Console.ReadLine(); 33 | if (userText.ToLower() != "quit") 34 | { 35 | // Call function to detect language 36 | await GetLanguage(userText); 37 | } 38 | 39 | } 40 | } 41 | catch (Exception ex) 42 | { 43 | Console.WriteLine(ex.Message); 44 | } 45 | } 46 | static async Task GetLanguage(string text) 47 | { 48 | // Construct the JSON request body 49 | try 50 | { 51 | JObject jsonBody = new JObject( 52 | // Create a collection of documents (we'll only use one, but you could have more) 53 | new JProperty("documents", 54 | new JArray( 55 | new JObject( 56 | // Each document needs a unique ID and some text 57 | new JProperty("id", 1), 58 | new JProperty("text", text) 59 | )))); 60 | 61 | // Encode as UTF-8 62 | UTF8Encoding utf8 = new UTF8Encoding(true, true); 63 | byte[] encodedBytes = utf8.GetBytes(jsonBody.ToString()); 64 | 65 | // Let's take a look at the JSON we'll send to the service 66 | Console.WriteLine(utf8.GetString(encodedBytes, 0, encodedBytes.Length)); 67 | 68 | // Make an HTTP request to the REST interface 69 | var client = new HttpClient(); 70 | var queryString = HttpUtility.ParseQueryString(string.Empty); 71 | 72 | // Add the authentication key to the header 73 | client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", AiSvCKey); 74 | 75 | // Use the endpoint to access the Text Analytics language API 76 | var uri = AiSvcEndpoint + "text/analytics/v3.1/languages?" + queryString; 77 | 78 | // Send the request and get the response 79 | HttpResponseMessage response; 80 | using (var content = new ByteArrayContent(encodedBytes)) 81 | { 82 | content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 83 | response = await client.PostAsync(uri, content); 84 | } 85 | 86 | // If the call was successful, get the response 87 | if (response.StatusCode == System.Net.HttpStatusCode.OK) 88 | { 89 | // Display the JSON response in full (just so we can see it) 90 | string responseContent = await response.Content.ReadAsStringAsync(); 91 | JObject results = JObject.Parse(responseContent); 92 | Console.WriteLine(results.ToString()); 93 | 94 | // Extract the detected language name for each document 95 | foreach (JObject document in results["documents"]) 96 | { 97 | Console.WriteLine("\nLanguage: " + (string)document["detectedLanguage"]["name"]); 98 | } 99 | } 100 | else 101 | { 102 | // Something went wrong, write the whole response 103 | Console.WriteLine(response.ToString()); 104 | } 105 | } 106 | catch(Exception ex) 107 | { 108 | Console.WriteLine(ex.Message); 109 | } 110 | 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/C-Sharp/rest-client/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "AIServicesEndpoint": "YOUR_AI_SERVICES_ENDPOINT", 3 | "AIServicesKey": "YOUR_AI_SERVICES_KEY" 4 | } -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/C-Sharp/rest-client/rest_client.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | rest_client 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | PreserveNewest 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/C-Sharp/sdk-client/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Azure; 3 | using Microsoft.Extensions.Configuration; 4 | using System.Text; 5 | using Azure.AI.TextAnalytics; 6 | 7 | namespace sdk_client 8 | { 9 | class Program 10 | { 11 | 12 | private static string AISvcEndpoint; 13 | private static string AISvcKey; 14 | static void Main(string[] args) 15 | { 16 | try 17 | { 18 | // Get config settings from AppSettings 19 | IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); 20 | IConfigurationRoot configuration = builder.Build(); 21 | AISvcEndpoint = configuration["AIServicesEndpoint"]; 22 | AISvcKey = configuration["AIServicesKey"]; 23 | 24 | // Get user input (until they enter "quit") 25 | string userText = ""; 26 | while (userText.ToLower() != "quit") 27 | { 28 | Console.WriteLine("\nEnter some text ('quit' to stop)"); 29 | userText = Console.ReadLine(); 30 | if (userText.ToLower() != "quit") 31 | { 32 | // Call function to detect language 33 | string language = GetLanguage(userText); 34 | Console.WriteLine("Language: " + language); 35 | } 36 | 37 | } 38 | } 39 | catch (Exception ex) 40 | { 41 | Console.WriteLine(ex.Message); 42 | } 43 | } 44 | static string GetLanguage(string text) 45 | { 46 | 47 | // Create client using endpoint and key 48 | AzureKeyCredential credentials = new AzureKeyCredential(AISvcKey); 49 | Uri endpoint = new Uri(AISvcEndpoint); 50 | var client = new TextAnalyticsClient(endpoint, credentials); 51 | 52 | // Call the service to get the detected language 53 | DetectedLanguage detectedLanguage = client.DetectLanguage(text); 54 | return(detectedLanguage.Name); 55 | 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/C-Sharp/sdk-client/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "AIServicesEndpoint": "YOUR_AI_SERVICES_ENDPOINT", 3 | "AIServicesKey": "YOUR_AI_SERVICES_KEY" 4 | } -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/C-Sharp/sdk-client/sdk-client.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | sdk_client 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | PreserveNewest 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/Python/readme.txt: -------------------------------------------------------------------------------- 1 | This folder contains Python code -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/Python/rest-client/.env: -------------------------------------------------------------------------------- 1 | AI_SERVICE_ENDPOINT=YOUR_AI_SERVICES_ENDPOINT 2 | AI_SERVICE_KEY=YOUR_AI_SERVICES_KEY -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/Python/rest-client/rest-client.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | import os 3 | import http.client, base64, json, urllib 4 | from urllib import request, parse, error 5 | 6 | def main(): 7 | global ai_endpoint 8 | global ai_key 9 | 10 | try: 11 | # Get Configuration Settings 12 | load_dotenv() 13 | ai_endpoint = os.getenv('AI_SERVICE_ENDPOINT') 14 | ai_key = os.getenv('AI_SERVICE_KEY') 15 | 16 | # Get user input (until they enter "quit") 17 | userText ='' 18 | while userText.lower() != 'quit': 19 | userText = input('Enter some text ("quit" to stop)\n') 20 | if userText.lower() != 'quit': 21 | GetLanguage(userText) 22 | 23 | 24 | except Exception as ex: 25 | print(ex) 26 | 27 | def GetLanguage(text): 28 | try: 29 | # Construct the JSON request body (a collection of documents, each with an ID and text) 30 | jsonBody = { 31 | "documents":[ 32 | {"id": 1, 33 | "text": text} 34 | ] 35 | } 36 | 37 | # Let's take a look at the JSON we'll send to the service 38 | print(json.dumps(jsonBody, indent=2)) 39 | 40 | # Make an HTTP request to the REST interface 41 | uri = ai_endpoint.rstrip('/').replace('https://', '') 42 | conn = http.client.HTTPSConnection(uri) 43 | 44 | # Add the authentication key to the request header 45 | headers = { 46 | 'Content-Type': 'application/json', 47 | 'Ocp-Apim-Subscription-Key': ai_key 48 | } 49 | 50 | # Use the Text Analytics language API 51 | conn.request("POST", "/text/analytics/v3.1/languages?", str(jsonBody).encode('utf-8'), headers) 52 | 53 | # Send the request 54 | response = conn.getresponse() 55 | data = response.read().decode("UTF-8") 56 | 57 | # If the call was successful, get the response 58 | if response.status == 200: 59 | 60 | # Display the JSON response in full (just so we can see it) 61 | results = json.loads(data) 62 | print(json.dumps(results, indent=2)) 63 | 64 | # Extract the detected language name for each document 65 | for document in results["documents"]: 66 | print("\nLanguage:", document["detectedLanguage"]["name"]) 67 | 68 | else: 69 | # Something went wrong, write the whole response 70 | print(data) 71 | 72 | conn.close() 73 | 74 | 75 | except Exception as ex: 76 | print(ex) 77 | 78 | 79 | if __name__ == "__main__": 80 | main() -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/Python/sdk-client/.env: -------------------------------------------------------------------------------- 1 | AI_SERVICE_ENDPOINT=YOUR_AI_SERVICES_ENDPOINT 2 | AI_SERVICE_KEY=YOUR_AI_SERVICES_KEY -------------------------------------------------------------------------------- /Labfiles/01-use-azure-ai-services/Python/sdk-client/sdk-client.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | import os 3 | from azure.core.credentials import AzureKeyCredential 4 | from azure.ai.textanalytics import TextAnalyticsClient 5 | 6 | def main(): 7 | global ai_endpoint 8 | global ai_key 9 | 10 | try: 11 | # Get Configuration Settings 12 | load_dotenv() 13 | ai_endpoint = os.getenv('AI_SERVICE_ENDPOINT') 14 | ai_key = os.getenv('AI_SERVICE_KEY') 15 | 16 | # Get user input (until they enter "quit") 17 | userText ='' 18 | while userText.lower() != 'quit': 19 | userText = input('\nEnter some text ("quit" to stop)\n') 20 | if userText.lower() != 'quit': 21 | language = GetLanguage(userText) 22 | print('Language:', language) 23 | 24 | except Exception as ex: 25 | print(ex) 26 | 27 | def GetLanguage(text): 28 | 29 | # Create client using endpoint and key 30 | credential = AzureKeyCredential(ai_key) 31 | client = TextAnalyticsClient(endpoint=ai_endpoint, credential=credential) 32 | 33 | # Call the service to get the detected language 34 | detectedLanguage = client.detect_language(documents = [text])[0] 35 | return detectedLanguage.primary_language.name 36 | 37 | 38 | if __name__ == "__main__": 39 | main() -------------------------------------------------------------------------------- /Labfiles/02-ai-services-security/C-Sharp/keyvault_client/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Azure; 3 | using Microsoft.Extensions.Configuration; 4 | using Azure.AI.TextAnalytics; 5 | using static System.Environment; 6 | using Azure.Identity; 7 | using Azure.Security.KeyVault.Secrets; 8 | 9 | namespace keyvault_client 10 | { 11 | class Program 12 | { 13 | 14 | private static string aiSvcEndpoint; 15 | private static string aiSvcKey; 16 | static void Main(string[] args) 17 | { 18 | try 19 | { 20 | // Get config settings from AppSettings 21 | IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); 22 | IConfigurationRoot configuration = builder.Build(); 23 | aiSvcEndpoint = configuration["AIServicesEndpoint"]; 24 | string keyVaultName = configuration["KeyVault"]; 25 | string appTenant = configuration["TenantId"]; 26 | string appId = configuration["AppId"]; 27 | string appPassword = configuration["AppPassword"]; 28 | 29 | // Get Azure AI services key from keyvault using the service principal credentials 30 | var keyVaultUri = new Uri($"https://{keyVaultName}.vault.azure.net/"); 31 | ClientSecretCredential credential = new ClientSecretCredential(appTenant, appId, appPassword); 32 | var keyVaultClient = new SecretClient(keyVaultUri, credential); 33 | KeyVaultSecret secretKey = keyVaultClient.GetSecret("AI-Services-Key"); 34 | aiSvcKey = secretKey.Value; 35 | 36 | // Get user input (until they enter "quit") 37 | string userText = ""; 38 | while (userText.ToLower() != "quit") 39 | { 40 | Console.WriteLine("\nEnter some text ('quit' to stop)"); 41 | userText = Console.ReadLine(); 42 | if (userText.ToLower() != "quit") 43 | { 44 | // Call function to detect language 45 | string language = GetLanguage(userText); 46 | Console.WriteLine("Language: " + language); 47 | } 48 | 49 | } 50 | } 51 | catch (Exception ex) 52 | { 53 | Console.WriteLine(ex.Message); 54 | } 55 | } 56 | static string GetLanguage(string text) 57 | { 58 | 59 | // Create client using endpoint and key 60 | AzureKeyCredential credentials = new AzureKeyCredential(aiSvcKey); 61 | Uri endpoint = new Uri(aiSvcEndpoint); 62 | var client = new TextAnalyticsClient(endpoint, credentials); 63 | 64 | // Call the service to get the detected language 65 | DetectedLanguage detectedLanguage = client.DetectLanguage(text); 66 | return(detectedLanguage.Name); 67 | 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Labfiles/02-ai-services-security/C-Sharp/keyvault_client/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "AIServicesEndpoint": "YOUR_AI_SERVICES_ENDPOINT", 3 | "KeyVault": "YOUR_KEY_VAULT_NAME", 4 | "TenantId": "YOUR_SERVICE_PRINCIPAL_TENANT_ID", 5 | "AppId": "YOUR_SERVICE_PRINCIPAL_APP_ID", 6 | "AppPassword": "YOUR_SERVICE_PRINCIPAL_PASSWORD" 7 | } -------------------------------------------------------------------------------- /Labfiles/02-ai-services-security/C-Sharp/keyvault_client/keyvault_client.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | keyvault_client 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | PreserveNewest 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Labfiles/02-ai-services-security/C-Sharp/readme.txt: -------------------------------------------------------------------------------- 1 | This folder contains C# code -------------------------------------------------------------------------------- /Labfiles/02-ai-services-security/Python/keyvault_client/.env: -------------------------------------------------------------------------------- 1 | AI_SERVICE_ENDPOINT=your_ai_services_endpoint 2 | KEY_VAULT=your_key_vault_name 3 | TENANT_ID=your_service_principal_tenant_id 4 | APP_ID=your_service_principal_app_id 5 | APP_PASSWORD=your_service_principal_password 6 | -------------------------------------------------------------------------------- /Labfiles/02-ai-services-security/Python/keyvault_client/keyvault-client.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | import os 3 | from azure.ai.textanalytics import TextAnalyticsClient 4 | from azure.core.credentials import AzureKeyCredential 5 | from azure.keyvault.secrets import SecretClient 6 | from azure.identity import ClientSecretCredential 7 | 8 | 9 | def main(): 10 | global ai_endpoint 11 | global cog_key 12 | 13 | try: 14 | # Get Configuration Settings 15 | load_dotenv() 16 | ai_endpoint = os.getenv('AI_SERVICE_ENDPOINT') 17 | key_vault_name = os.getenv('KEY_VAULT') 18 | app_tenant = os.getenv('TENANT_ID') 19 | app_id = os.getenv('APP_ID') 20 | app_password = os.getenv('APP_PASSWORD') 21 | 22 | # Get Azure AI services key from keyvault using the service principal credentials 23 | key_vault_uri = f"https://{key_vault_name}.vault.azure.net/" 24 | credential = ClientSecretCredential(app_tenant, app_id, app_password) 25 | keyvault_client = SecretClient(key_vault_uri, credential) 26 | secret_key = keyvault_client.get_secret("AI-Services-Key") 27 | cog_key = secret_key.value 28 | 29 | # Get user input (until they enter "quit") 30 | userText ='' 31 | while userText.lower() != 'quit': 32 | userText = input('\nEnter some text ("quit" to stop)\n') 33 | if userText.lower() != 'quit': 34 | language = GetLanguage(userText) 35 | print('Language:', language) 36 | 37 | except Exception as ex: 38 | print(ex) 39 | 40 | def GetLanguage(text): 41 | 42 | # Create client using endpoint and key 43 | credential = AzureKeyCredential(cog_key) 44 | client = TextAnalyticsClient(endpoint=ai_endpoint, credential=credential) 45 | 46 | # Call the service to get the detected language 47 | detectedLanguage = client.detect_language(documents = [text])[0] 48 | return detectedLanguage.primary_language.name 49 | 50 | 51 | if __name__ == "__main__": 52 | main() -------------------------------------------------------------------------------- /Labfiles/02-ai-services-security/Python/readme.txt: -------------------------------------------------------------------------------- 1 | This folder contains Python code -------------------------------------------------------------------------------- /Labfiles/02-ai-services-security/rest-test.cmd: -------------------------------------------------------------------------------- 1 | curl -X POST "/language/:analyze-text?api-version=2023-04-01" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: " --data-ascii "{'analysisInput':{'documents':[{'id':1,'text':'hello'}]}, 'kind': 'LanguageDetection'}" -------------------------------------------------------------------------------- /Labfiles/02-ai-services-security/rest-test.sh: -------------------------------------------------------------------------------- 1 | curl -X POST "/text/analytics/v3.1/languages?'" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: " --data-ascii "{'documents':[{'id':1,'text':'hello'}]}" -------------------------------------------------------------------------------- /Labfiles/03-monitor-ai-services/rest-test.cmd: -------------------------------------------------------------------------------- 1 | curl -X POST "/language/:analyze-text?api-version=2023-04-01" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: " --data-ascii "{'analysisInput':{'documents':[{'id':1,'text':'hello'}]}, 'kind': 'LanguageDetection'}" -------------------------------------------------------------------------------- /Labfiles/03-monitor-ai-services/rest-test.sh: -------------------------------------------------------------------------------- 1 | curl -X POST "/text/analytics/v3.1/languages?" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: " --data-ascii "{'documents': [{'id':1,'text':'hello'}]}" -------------------------------------------------------------------------------- /Labfiles/04-use-a-container/rest-test.cmd: -------------------------------------------------------------------------------- 1 | curl -X POST "http://:5000/text/analytics/v3.1/sentiment" -H "Content-Type: application/json" --data-ascii "{'documents':[{'id':1,'text':'The performance was amazing! The sound could have been clearer.'},{'id':2,'text':'The food and service were unacceptable. While the host was nice, the waiter was rude and food was cold.'}]}" 2 | -------------------------------------------------------------------------------- /Labfiles/05-implement-content-safety/C-Sharp/Program.cs: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /Labfiles/05-implement-content-safety/C-Sharp/prompt_shield.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | C-Sharp 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Labfiles/05-implement-content-safety/C-Sharp/readme.txt: -------------------------------------------------------------------------------- 1 | This folder contains C# code -------------------------------------------------------------------------------- /Labfiles/05-implement-content-safety/Python/prompt-shield.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicrosoftLearning/mslearn-ai-services/06023ca8fd67552a097666162ef613fd98efae33/Labfiles/05-implement-content-safety/Python/prompt-shield.py -------------------------------------------------------------------------------- /Labfiles/05-implement-content-safety/Python/readme.txt: -------------------------------------------------------------------------------- 1 | This folder contains Python code -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Develop Generative AI Solutions in Azure 2 | 3 | The exercises in this repo are designed to provide you with a hands-on learning experience in which you'll explore common tasks that developers perform when building generative AI solutions on Microsoft Azure. 4 | 5 | > **Note**: To complete the exercises, you'll need an Azure subscription in which you have sufficient permissions and quota to provision the necessary Azure resources and generative AI models. If you don't already have one, you can sign up for an [Azure account](https://azure.microsoft.com/free). There's a free trial option for new users that includes credits for the first 30 days. 6 | 7 | View the exercises in the [GitHub Pages site for this repo](https://microsoftlearning.github.io/mslearn-ai-services/). 8 | 9 | 10 | > **Note**: While you can complete these exercises on their own, they're designed to complement modules on [Microsoft Learn](https://learn.microsoft.com/training/paths/get-started-azure-ai/); in which you'll find a deeper dive into some of the underlying concepts on which these exercises are based. 11 | 12 | ## Reporting issues 13 | 14 | If you encounter any problems in the exercises, please report them as **issues** in this repo. 15 | -------------------------------------------------------------------------------- /_build.yml: -------------------------------------------------------------------------------- 1 | name: '$(Date:yyyyMMdd)$(Rev:.rr)' 2 | jobs: 3 | - job: build_markdown_content 4 | displayName: 'Build Markdown Content' 5 | workspace: 6 | clean: all 7 | pool: 8 | vmImage: 'Ubuntu 16.04' 9 | container: 10 | image: 'microsoftlearning/markdown-build:latest' 11 | steps: 12 | - task: Bash@3 13 | displayName: 'Build Content' 14 | inputs: 15 | targetType: inline 16 | script: | 17 | cp /{attribution.md,template.docx,package.json,package.js} . 18 | npm install 19 | node package.js --version $(Build.BuildNumber) 20 | - task: GitHubRelease@0 21 | displayName: 'Create GitHub Release' 22 | inputs: 23 | gitHubConnection: 'github-microsoftlearning-organization' 24 | repositoryName: '$(Build.Repository.Name)' 25 | tagSource: manual 26 | tag: 'v$(Build.BuildNumber)' 27 | title: 'Version $(Build.BuildNumber)' 28 | releaseNotesSource: input 29 | releaseNotes: '# Version $(Build.BuildNumber) Release' 30 | assets: '$(Build.SourcesDirectory)/out/*.zip' 31 | assetUploadMode: replace 32 | - task: PublishBuildArtifacts@1 33 | displayName: 'Publish Output Files' 34 | inputs: 35 | pathtoPublish: '$(Build.SourcesDirectory)/out/' 36 | artifactName: 'Lab Files' 37 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | remote_theme: MicrosoftLearning/Jekyll-Theme 2 | exclude: 3 | - readme.md 4 | - .github/ 5 | header_pages: 6 | - index.html 7 | author: Microsoft Learning 8 | twitter_username: mslearning 9 | github_username: MicrosoftLearning 10 | plugins: 11 | - jekyll-sitemap 12 | - jekyll-mentions 13 | - jemoji 14 | markdown: kramdown 15 | kramdown: 16 | syntax_highlighter_opts: 17 | disable : true 18 | -------------------------------------------------------------------------------- /index.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Get started with Azure AI Services 3 | permalink: index.html 4 | layout: home 5 | --- 6 | 7 | The following exercises are designed to provide you with a hands-on learning experience in which you'll explore common tasks that developers perform when creating generative AI solutions on Microsoft Azure. 8 | 9 | > **Note**: To complete the exercises, you'll need an Azure subscription in which you have sufficient permissions and quota to provision the necessary Azure resources and generative AI models. If you don't already have one, you can sign up for an [Azure account](https://azure.microsoft.com/free). There's a free trial option for new users that includes credits for the first 30 days. 10 | 11 | ## Exercises 12 | 13 | {% assign labs = site.pages | where_exp:"page", "page.url contains '/Instructions/Labs'" %} 14 | {% for activity in labs %} 15 |
16 | ### [{{ activity.lab.title }}]({{ site.github.url }}{{ activity.url }}) 17 | {{activity.lab.description}} 18 | {% endfor %} 19 | 20 | > **Note**: While you can complete these exercises on their own, they're designed to complement modules on [Microsoft Learn](https://learn.microsoft.com/training/paths/get-started-azure-ai/); in which you'll find a deeper dive into some of the underlying concepts on which these exercises are based. 21 | --------------------------------------------------------------------------------