Chat

chatgptopenaigpt-4examplesazureopenai-apiopenai-cookbook

Azure chat completions example

This example will cover chat completions using the Azure OpenAI service. It also includes information on content filtering.

Setup

First, we install the necessary dependencies and import the libraries we will be using.

[ ]
[ ]

Authentication

The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure Active Directory token credentials.

[2]

Authentication using API key

To set up the OpenAI SDK to use an Azure API Key, we need to set api_key to a key associated with your endpoint (you can find this key in "Keys and Endpoints" under "Resource Management" in the Azure Portal). You'll also find the endpoint for your resource here.

[13]

Authentication using Azure Active Directory

Let's now see how we can autheticate via Azure Active Directory. We'll start by installing the azure-identity library. This library will provide the token credentials we need to authenticate and help us build a token credential provider through the get_bearer_token_provider helper function. It's recommended to use get_bearer_token_provider over providing a static token to AzureOpenAI because this API will automatically cache and refresh tokens for you.

For more information on how to set up Azure Active Directory authentication with Azure OpenAI, see the documentation.

[ ]
[5]

Note: the AzureOpenAI infers the following arguments from their corresponding environment variables if they are not provided:

  • api_key from AZURE_OPENAI_API_KEY
  • azure_ad_token from AZURE_OPENAI_AD_TOKEN
  • api_version from OPENAI_API_VERSION
  • azure_endpoint from AZURE_OPENAI_ENDPOINT

Deployments

In this section we are going to create a deployment of a GPT model that we can use to create chat completions.

Deployments: Create in the Azure OpenAI Studio

Let's deploy a model to use with chat completions. Go to https://portal.azure.com, find your Azure OpenAI resource, and then navigate to the Azure OpenAI Studio. Click on the "Deployments" tab and then create a deployment for the model you want to use for chat completions. The deployment name that you give the model will be used in the code below.

[4]

Create chat completions

Now let's create a chat completion using the client we built.

[ ]

Create a streaming chat completion

We can also stream the response.

[ ]

Content filtering

Azure OpenAI service includes content filtering of prompts and completion responses. You can learn more about content filtering and how to configure it here.

If the prompt is flagged by the content filter, the library will raise a BadRequestError exception with a content_filter error code. Otherwise, you can access the prompt_filter_results and content_filter_results on the response to see the results of the content filtering and what categories were flagged.

Prompt flagged by content filter

[ ]

Checking the result of the content filter

[ ]