#Note: The openai-python library support for Azure OpenAI is in preview.
import os
import openai
openai.api_type = "azure"
openai.api_base = "https://docs-test-001.openai.azure.com/"
openai.api_version = "2023-05-15"
openai.api_key = os.getenv("OPENAI_API_KEY")
response = openai.ChatCompletion.create(
engine="gpt-35-turbo", # replace this value with the deployment name you chose when you deployed the associated model.
messages = [{"role":"system","content":"You are an Xbox customer support agent whose primary goal is to help users with issues they are experiencing with their Xbox devices. You are friendly and concise. You only provide factual answers to queries, and do not provide answers that are not related to Xbox."},{"role":"user","content":"How much is a PS5?"},{"role":"assistant","content":"I apologize, but I do not have information about the prices of other gaming devices such as the PS5. My primary focus is to assist with issues regarding Xbox devices. Is there a specific issue you are having with your Xbox device that I may be able to help with?"},{"role":"user","content":"I am interested in buying an Xbox?"},{"role":"assistant","content":"Great! There are several Xbox models available in the market, including the Xbox Series X, Xbox Series S, and Xbox One. The Xbox Series X is the latest and most powerful console, while the Xbox Series S is a more affordable option that still offers great performance. The Xbox One is the previous generation console, but it still has a large library of games available to play.\n\nBefore purchasing an Xbox, you may want to consider factors such as your budget, the types of games you want to play, and whether you want to play games in 4K resolution. Once you have decided on a console, you can purchase it from a retailer or directly from the Xbox website. Let me know if you have any other questions or concerns!"},{"role":"user","content":"Which models are 4K?"},{"role":"assistant","content":"Both the Xbox Series X and Xbox One X support 4K resolution gaming. The Xbox Series S, on the other hand, supports up to 1440p resolution gaming, but it can upscale games to 4K. It's worth noting that in order to take advantage of 4K gaming, you'll need a 4K TV or monitor that supports HDR (High Dynamic Range) and HDMI 2.0 or higher."}],
temperature=0,
max_tokens=350,
top_p=0.95,
frequency_penalty=0,
presence_penalty=0,
stop=None)
I ran into an issue with the playground.
Understanding the prompt structure
If you examine the sample from View code you'll notice some unique tokens that weren't part of a typical GPT completion call. GPT-35-Turbo was trained to use special tokens to delineate different parts of the prompt. Content is provided to the model in between <|im_start|>
and <|im_end|>
tokens. The prompt begins with a system message that can be used to prime the model by including context or instructions for the model. After that, the prompt contains a series of messages between the user and the assistant.
The assistant's response to the prompt will then be returned below the <|im_start|>assistant
token and will end with <|im_end|>
denoting that the assistant has finished its response. You can also use the Show raw syntax toggle button to display these tokens within the chat session panel.
The GPT-35-Turbo & GPT-4 how-to guide provides an in-depth introduction into the new prompt structure and how to use the gpt-35-turbo
model effectively.
Deploy a web app
Once you're satisfied with the experience in Azure OpenAI studio, you can deploy a web app directly from the
Studio by selecting the Deploy to button.
The first time you deploy a web app, you should select Create a new web app. Choose a name for the app, which will
become part of the app URL. For example, https://<appname>.azurewebsites.net
.
Select your subscription, resource group, location, and pricing plan for the published app. To
update an existing app, select Publish to an existing web app and choose the name of your previous
app from the dropdown menu.
I ran into an issue with the web app.
Clean up resources
Once you're done testing out the Chat playground, if you want to clean up and remove an OpenAI resource, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.
Portal
Azure CLI
Next steps
Learn more about how to work with the new gpt-35-turbo
model with the GPT-35-Turbo & GPT-4 how-to guide.
For more examples check out the Azure OpenAI Samples GitHub repository
Source code | Package (NuGet) | Samples
Prerequisites
An Azure subscription - Create one for free
Access granted to the Azure OpenAI service in the desired Azure subscription.
Currently, access to this service is granted only by application. You can apply for access to Azure OpenAI Service by completing the form at https://aka.ms/oai/access.
The .NET 7 SDK
An Azure OpenAI Service resource with either the gpt-35-turbo
or the gpt-4
1 models deployed. For more information about model deployment, see the resource deployment guide.
1 GPT-4 models are currently only available by request. Existing Azure OpenAI customers can apply for access by filling out this form.
I ran into an issue with the prerequisites.
Set up
Create a new .NET Core application
In a console window (such as cmd, PowerShell, or Bash), use the dotnet new
command to create a new console app with the name azure-openai-quickstart
. This command creates a simple "Hello World" project with a single C# source file: Program.cs.
dotnet new console -n azure-openai-quickstart
Change your directory to the newly created app folder. You can build the application with:
dotnet build
The build output should contain no warnings or errors.
Build succeeded.
0 Warning(s)
0 Error(s)
Install the OpenAI .NET client library with:
dotnet add package Azure.AI.OpenAI --prerelease
Retrieve key and endpoint
To successfully make a call against Azure OpenAI, you need an endpoint and a key.
Variable name
Value
ENDPOINT
This value can be found in the Keys & Endpoint section when examining your resource from the Azure portal. Alternatively, you can find the value in the Azure OpenAI Studio > Playground > Code View. An example endpoint is: https://docs-test-001.openai.azure.com/
.
API-KEY
This value can be found in the Keys & Endpoint section when examining your resource from the Azure portal. You can use either KEY1
or KEY2
.
Go to your resource in the Azure portal. The Endpoint and Keys can be found in the Resource Management section. Copy your endpoint and access key as you'll need both for authenticating your API calls. You can use either KEY1
or KEY2
. Always having two keys allows you to securely rotate and regenerate keys without causing a service disruption.
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_KEY', 'REPLACE_WITH_YOUR_KEY_VALUE_HERE', 'User')
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_ENDPOINT', 'REPLACE_WITH_YOUR_ENDPOINT_HERE', 'User')
echo export AZURE_OPENAI_KEY="REPLACE_WITH_YOUR_KEY_VALUE_HERE" >> /etc/environment && source /etc/environment
echo export AZURE_OPENAI_ENDPOINT="REPLACE_WITH_YOUR_ENDPOINT_HERE" >> /etc/environment && source /etc/environment
Create .NET application
From the project directory, open the program.cs file and replace with the following code:
Without response streaming
using Azure;
using Azure.AI.OpenAI;
using static System.Environment;
string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
string key = GetEnvironmentVariable("AZURE_OPENAI_KEY");
OpenAIClient client = new(new Uri(endpoint), new AzureKeyCredential(key));
var chatCompletionsOptions = new ChatCompletionsOptions()
Messages =
new ChatMessage(ChatRole.System, "You are a helpful assistant."),
new ChatMessage(ChatRole.User, "Does Azure OpenAI support customer managed keys?"),
new ChatMessage(ChatRole.Assistant, "Yes, customer managed keys are supported by Azure OpenAI."),
new ChatMessage(ChatRole.User, "Do other Azure Cognitive Services support this too?"),
MaxTokens = 100
Response<ChatCompletions> response = client.GetChatCompletions(
deploymentOrModelName: "gpt-35-turbo",
chatCompletionsOptions);
Console.WriteLine(response.Value.Choices[0].Message.Content);
Console.WriteLine();
Important
For production, use a secure way of storing and accessing your credentials like Azure Key Vault. For more information about credential security, see the Cognitive Services security article.
dotnet run program.cs
Output
Yes, many of the Azure Cognitive Services support customer managed keys. Some examples include Azure Cognitive Services Text Analytics, Speech Services, and Translator. However, it's important to note that not all services support customer managed keys, so it's best to check the documentation for each individual service to see if it is supported.
This will wait until the model has generated its entire response before printing the results. Alternatively, if you want to asynchronously stream the response and print the results, you can replace the contents of program.cs with the code in the next example.
Async with streaming
using Azure;
using Azure.AI.OpenAI;
using static System.Environment;
string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
string key = GetEnvironmentVariable("AZURE_OPENAI_KEY");
OpenAIClient client = new(new Uri(endpoint), new AzureKeyCredential(key));
var chatCompletionsOptions = new ChatCompletionsOptions()
Messages =
new ChatMessage(ChatRole.System, "You are a helpful assistant."),
new ChatMessage(ChatRole.User, "Does Azure OpenAI support customer managed keys?"),
new ChatMessage(ChatRole.Assistant, "Yes, customer managed keys are supported by Azure OpenAI."),
new ChatMessage(ChatRole.User, "Do other Azure Cognitive Services support this too?"),
MaxTokens = 100
Response<StreamingChatCompletions> response = await client.GetChatCompletionsStreamingAsync(
deploymentOrModelName: "gpt-35-turbo",
chatCompletionsOptions);
using StreamingChatCompletions streamingChatCompletions = response.Value;
await foreach (StreamingChatChoice choice in streamingChatCompletions.GetChoicesStreaming())
await foreach (ChatMessage message in choice.GetMessageStreaming())
Console.Write(message.Content);
Console.WriteLine();
I ran into an issue when running the code samples.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource. Before deleting the resource, you must first delete any deployed models.
Portal
Azure CLI
Next steps
For more examples, check out the Azure OpenAI Samples GitHub repository
Source code | Artifact (Maven) | Samples
Prerequisites
An Azure subscription - Create one for free
Access granted to the Azure OpenAI service in the desired Azure subscription.
Currently, access to this service is granted only by application. You can apply for access to Azure OpenAI Service by completing the form at https://aka.ms/oai/access.
Java Development Kit (JDK) with version 8 or above.
An Azure OpenAI Service resource with either the gpt-35-turbo
or the gpt-4
1 models deployed. For more information about model deployment, see the resource deployment guide.
1 GPT-4 models are currently only available by request. Existing Azure OpenAI customers can apply for access by filling out this form.
I ran into an issue with the prerequisites.
Set up
Install Apache Maven. Then run mvn -v
to confirm successful installation. The README.txt
file from the installation has instructions on adding the Maven bin directory to your PATH variable. If you don't set this the mvn
command will instead need to run like c:\apache-maven-3.9.2-bin\apache-maven-3.9.2\mvn -v
.
Create the directory structure for your project.
mkdir "quickstart/src/main/java/com/azure/ai/openai/usage"
At the root of the quickstart directory, create a file named pom.xml
with the following content:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.azure.ai.openai.usage.GetChatCompletionsSample</groupId>
<artifactId>quickstart-eclipse</artifactId>
<version>1.0.0-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-openai</artifactId>
<version>1.0.0-beta.1</version>
</dependency>
</dependencies>
</project>
Retrieve key and endpoint
To successfully make a call against Azure OpenAI, you need an endpoint and a key.
Variable name
Value
ENDPOINT
This value can be found in the Keys & Endpoint section when examining your resource from the Azure portal. Alternatively, you can find the value in the Azure AI Studio > Playground > Code View. An example endpoint is: https://docs-test-001.openai.azure.com/
.
API-KEY
This value can be found in the Keys & Endpoint section when examining your resource from the Azure portal. You can use either KEY1
or KEY2
.
Go to your resource in the Azure portal. The Endpoint and Keys can be found in the Resource Management section. Copy your endpoint and access key as you'll need both for authenticating your API calls. You can use either KEY1
or KEY2
. Always having two keys allows you to securely rotate and regenerate keys without causing a service disruption.
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_KEY', 'REPLACE_WITH_YOUR_KEY_VALUE_HERE', 'User')
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_ENDPOINT', 'REPLACE_WITH_YOUR_ENDPOINT_HERE', 'User')
echo export AZURE_OPENAI_KEY="REPLACE_WITH_YOUR_KEY_VALUE_HERE" >> /etc/environment && source /etc/environment
echo export AZURE_OPENAI_ENDPOINT="REPLACE_WITH_YOUR_ENDPOINT_HERE" >> /etc/environment && source /etc/environment
Create a sample application
Create a new file named GetChatCompletionsSample.java
and place it in quickstart/src/main/java/com/azure/ai/openai/usage
folder. Copy the following code into the file.
package com.azure.ai.openai.usage;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.ai.openai.models.ChatChoice;
import com.azure.ai.openai.models.ChatCompletions;
import com.azure.ai.openai.models.ChatCompletionsOptions;
import com.azure.ai.openai.models.ChatMessage;
import com.azure.ai.openai.models.ChatRole;
import com.azure.ai.openai.models.CompletionsUsage;
import com.azure.core.credential.AzureKeyCredential;
import java.util.ArrayList;
import java.util.List;
public class GetChatCompletionsSample {
public static void main(String[] args) {
String azureOpenaiKey = System.getenv("AZURE_OPENAI_KEY");;
String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT");;
String deploymentOrModelId = "gpt-35-turbo";
OpenAIClient client = new OpenAIClientBuilder()
.endpoint(endpoint)
.credential(new AzureKeyCredential(azureOpenaiKey))
.buildClient();
List<ChatMessage> chatMessages = new ArrayList<>();
chatMessages.add(new ChatMessage(ChatRole.SYSTEM).setContent("You are a helpful assistant."));
chatMessages.add(new ChatMessage(ChatRole.USER).setContent("Does Azure OpenAI support customer managed keys?"));
chatMessages.add(new ChatMessage(ChatRole.ASSISTANT).setContent("Yes, customer managed keys are supported by Azure OpenAI?"));
chatMessages.add(new ChatMessage(ChatRole.USER).setContent("Do other Azure Cognitive Services support this too?"));
ChatCompletions chatCompletions = client.getChatCompletions(deploymentOrModelId, new ChatCompletionsOptions(chatMessages));
System.out.printf("Model ID=%s is created at %d.%n", chatCompletions.getId(), chatCompletions.getCreated());
for (ChatChoice choice : chatCompletions.getChoices()) {
ChatMessage message = choice.getMessage();
System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole());
System.out.println("Message:");
System.out.println(message.getContent());
System.out.println();
CompletionsUsage usage = chatCompletions.getUsage();
System.out.printf("Usage: number of prompt token is %d, "
+ "number of completion token is %d, and number of total tokens in request and response is %d.%n",
usage.getPromptTokens(), usage.getCompletionTokens(), usage.getTotalTokens());
Important
For production, use a secure way of storing and accessing your credentials like Azure Key Vault. For more information about credential security, see the Cognitive Services security article.
From the top level quickstart directory where your pom.xml
is located run:
mvn compile
Now run the sample:
mvn exec:java -Dexec.mainClass="com.azure.ai.openai.usage.GetChatCompletionsSample"
Output
Model ID=chatcmpl-7JYnyE4zpd5gaIfTRH7hNpeVsvAw4 is created at 1684896378.
Index: 0, Chat Role: assistant.
Message:
Yes, most of the Azure Cognitive Services support customer managed keys. However, there may be some exceptions, so it is best to check the documentation of each specific service to confirm.
Usage: number of prompt token is 59, number of completion token is 36, and number of total tokens in request and response is 95.
I ran into an issue when running the code sample.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource. Before deleting the resource, you must first delete any deployed models.
Portal
Azure CLI
Next steps
For more examples, check out the Azure OpenAI Samples GitHub repository
Source code | Package (npm) | Samples
Prerequisites
An Azure subscription - Create one for free
Access granted to the Azure OpenAI service in the desired Azure subscription.
Currently, access to this service is granted only by application. You can apply for access to Azure OpenAI Service by completing the form at https://aka.ms/oai/access.
LTS versions of Node.js
An Azure OpenAI Service resource with either the gpt-35-turbo
or the gpt-4
1 models deployed. For more information about model deployment, see the resource deployment guide.
1 GPT-4 models are currently only available by request. Existing Azure OpenAI customers can apply for access by filling out this form.
I ran into an issue with the prerequisites.
Set up
Install the client library
Create a new directory and navigate into that directory.
Install the Azure OpenAI client library for JavaScript with npm:
npm install @azure/openai
Retrieve key and endpoint
To successfully make a call against Azure OpenAI, you need an endpoint and a key.
Variable name
Value
ENDPOINT
This value can be found in the Keys & Endpoint section when examining your resource from the Azure portal. Alternatively, you can find the value in the Azure OpenAI Studio > Playground > Code View. An example endpoint is: https://docs-test-001.openai.azure.com/
.
API-KEY
This value can be found in the Keys & Endpoint section when examining your resource from the Azure portal. You can use either KEY1
or KEY2
.
Go to your resource in the Azure portal. The Endpoint and Keys can be found in the Resource Management section. Copy your endpoint and access key as you'll need both for authenticating your API calls. You can use either KEY1
or KEY2
. Always having two keys allows you to securely rotate and regenerate keys without causing a service disruption.
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_KEY', 'REPLACE_WITH_YOUR_KEY_VALUE_HERE', 'User')
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_ENDPOINT', 'REPLACE_WITH_YOUR_ENDPOINT_HERE', 'User')
echo export AZURE_OPENAI_KEY="REPLACE_WITH_YOUR_KEY_VALUE_HERE" >> /etc/environment && source /etc/environment
echo export AZURE_OPENAI_ENDPOINT="REPLACE_WITH_YOUR_ENDPOINT_HERE" >> /etc/environment && source /etc/environment
Create a sample application
Open a command prompt where you want the new project, and create a new file named ChatCompletion.js. Copy the following code into the ChatCompletion.js file.
const { OpenAIClient, AzureKeyCredential } = require("@azure/openai");
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] ;
const azureApiKey = process.env["AZURE_OPENAI_KEY"] ;
const messages = [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Does Azure OpenAI support customer managed keys?" },
{ role: "assistant", content: "Yes, customer managed keys are supported by Azure OpenAI" },
{ role: "user", content: "Do other Azure Cognitive Services support this too" },
async function main() {
console.log("== Chat Completions Sample ==");
const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
const deploymentId = "gpt-35-turbo";
const result = await client.getChatCompletions(deploymentId, messages);
for (const choice of result.choices) {
console.log(choice.message);
main().catch((err) => {
console.error("The sample encountered an error:", err);
module.exports = { main };
Important
For production, use a secure way of storing and accessing your credentials like Azure Key Vault. For more information about credential security, see the Cognitive Services security article.
node.exe ChatCompletion.js
Output
== Chat Completions Sample ==
role: 'assistant',
content: 'Yes, most Azure Cognitive Services support customer managed keys. It is always best to check the specific service documentation to confirm this.'
I ran into an issue when running the code sample.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource. Before deleting the resource, you must first delete any deployed models.
Portal
Azure CLI
Next steps
For more examples, check out the Azure OpenAI Samples GitHub repository
Library source code | Package (PyPi) |
Prerequisites
An Azure subscription - Create one for free
Access granted to Azure OpenAI Service in the desired Azure subscription.
Currently, access to this service is granted only by application. You can apply for access to Azure OpenAI Service by completing the form at https://aka.ms/oai/access.
Python 3.7.1 or later version.
The following Python libraries: os.
An Azure OpenAI Service resource with either the gpt-35-turbo
or the gpt-4
1 models deployed. For more information about model deployment, see the resource deployment guide.
1 GPT-4 models are currently only available by request. Existing Azure OpenAI customers can apply for access by filling out this form.
I ran into an issue with the prerequisites.
Set up
Install the OpenAI Python client library with:
pip install openai
This library is maintained by OpenAI and is currently in preview. Refer to the release history or the version.py commit history to track the latest updates to the library.
Retrieve key and endpoint
To successfully make a call against Azure OpenAI, you'll need an endpoint and a key.
Variable name
Value
ENDPOINT
This value can be found in the Keys & Endpoint section when examining your resource from the Azure portal. Alternatively, you can find the value in the Azure OpenAI Studio > Playground > Code View. An example endpoint is: https://docs-test-001.openai.azure.com/
.
API-KEY
This value can be found in the Keys & Endpoint section when examining your resource from the Azure portal. You can use either KEY1
or KEY2
.
Go to your resource in the Azure portal. The Endpoint and Keys can be found in the Resource Management section. Copy your endpoint and access key as you'll need both for authenticating your API calls. You can use either KEY1
or KEY2
. Always having two keys allows you to securely rotate and regenerate keys without causing a service disruption.
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_KEY', 'REPLACE_WITH_YOUR_KEY_VALUE_HERE', 'User')
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_ENDPOINT', 'REPLACE_WITH_YOUR_ENDPOINT_HERE', 'User')
echo export AZURE_OPENAI_KEY="REPLACE_WITH_YOUR_KEY_VALUE_HERE" >> /etc/environment && source /etc/environment
echo export AZURE_OPENAI_ENDPOINT="REPLACE_WITH_YOUR_ENDPOINT_HERE" >> /etc/environment && source /etc/environment
Create a new Python application
Create a new Python file called quickstart.py. Then open it up in your preferred editor or IDE.
Replace the contents of quickstart.py with the following code. You need to set the engine
variable to the deployment name you chose when you deployed the GPT-35-Turbo or GPT-4 models. Entering the model name will result in an error unless you chose a deployment name that is identical to the underlying model name.
#Note: The openai-python library support for Azure OpenAI is in preview.
import os
import openai
openai.api_type = "azure"
openai.api_base = os.getenv("AZURE_OPENAI_ENDPOINT")
openai.api_version = "2023-05-15"
openai.api_key = os.getenv("AZURE_OPENAI_KEY")
response = openai.ChatCompletion.create(
engine="gpt-35-turbo", # engine = "deployment_name".
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Does Azure OpenAI support customer managed keys?"},
{"role": "assistant", "content": "Yes, customer managed keys are supported by Azure OpenAI."},
{"role": "user", "content": "Do other Azure Cognitive Services support this too?"}
print(response)
print(response['choices'][0]['message']['content'])
Important
For production, use a secure way of storing and accessing your credentials like Azure Key Vault. For more information about credential security, see the Cognitive Services security article.
Run the application with the python
command on your quickstart file:
python quickstart.py
Output
"choices": [
"finish_reason": "stop",
"index": 0,
"message": {
"content": "Yes, most of the Azure Cognitive Services support customer managed keys. However, not all services support it. You can check the documentation of each service to confirm if customer managed keys are supported.",
"role": "assistant"
"created": 1679001781,
"id": "chatcmpl-6upLpNYYOx2AhoOYxl9UgJvF4aPpR",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion",
"usage": {
"completion_tokens": 39,
"prompt_tokens": 58,
"total_tokens": 97
Yes, most of the Azure Cognitive Services support customer managed keys. However, not all services support it. You can check the documentation of each service to confirm if customer managed keys are supported.
I ran into an issue when running the code sample.
Understanding the message structure
The GPT-35-Turbo and GPT-4 models are optimized to work with inputs formatted as a conversation. The messages
variable passes an array of dictionaries with different roles in the conversation delineated by system, user, and assistant. The system message can be used to prime the model by including context or instructions on how the model should respond.
The GPT-35-Turbo & GPT-4 how-to guide provides an in-depth introduction into the options for communicating with these new models.
Clean up resources
If you want to clean up and remove an OpenAI resource, you can delete the resource. Before deleting the resource, you must first delete any deployed models.
Portal
Azure CLI
Next steps
Learn more about how to work with GPT-35-Turbo and the GPT-4 models with our how-to guide.
For more examples, check out the Azure OpenAI Samples GitHub repository
REST API Spec |
Prerequisites
An Azure subscription - Create one for free.
Access granted to Azure OpenAI Service in the desired Azure subscription.
Currently, access to this service is granted only by application. You can apply for access to Azure OpenAI Service by completing the form at https://aka.ms/oai/access.
An Azure OpenAI Service resource with either the gpt-35-turbo
or the gpt-4
1 models deployed. For more information about model deployment, see the resource deployment guide.
1 GPT-4 models are currently only available by request. To access these models, existing Azure OpenAI customers can apply for access by filling out this form.
Set up
Retrieve key and endpoint
To successfully make a call against Azure OpenAI, you'll need an endpoint and a key.
Variable name
Value
ENDPOINT
This value can be found in the Keys & Endpoint section when examining your resource from the Azure portal. Alternatively, you can find the value in the Azure OpenAI Studio > Playground > Code View. An example endpoint is: https://docs-test-001.openai.azure.com/
.
API-KEY
This value can be found in the Keys & Endpoint section when examining your resource from the Azure portal. You can use either KEY1
or KEY2
.
Go to your resource in the Azure portal. The Endpoint and Keys can be found in the Resource Management section. Copy your endpoint and access key as you'll need both for authenticating your API calls. You can use either KEY1
or KEY2
. Always having two keys allows you to securely rotate and regenerate keys without causing a service disruption.
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_KEY', 'REPLACE_WITH_YOUR_KEY_VALUE_HERE', 'User')
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_ENDPOINT', 'REPLACE_WITH_YOUR_ENDPOINT_HERE', 'User')
echo export AZURE_OPENAI_KEY="REPLACE_WITH_YOUR_KEY_VALUE_HERE" >> /etc/environment && source /etc/environment
echo export AZURE_OPENAI_ENDPOINT="REPLACE_WITH_YOUR_ENDPOINT_HERE" >> /etc/environment && source /etc/environment
REST API
In a bash shell, run the following command. You will need to replace gpt-35-turbo
with the deployment name you chose when you deployed the GPT-35-Turbo or GPT-4 models. Entering the model name will result in an error unless you chose a deployment name that is identical to the underlying model name.
curl $AZURE_OPENAI_ENDPOINT/openai/deployments/gpt-35-turbo/chat/completions?api-version=2023-05-15 \
-H "Content-Type: application/json" \
-H "api-key: $AZURE_OPENAI_KEY" \
-d '{"messages":[{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Does Azure OpenAI support customer managed keys?"},{"role": "assistant", "content": "Yes, customer managed keys are supported by Azure OpenAI."},{"role": "user", "content": "Do other Azure Cognitive Services support this too?"}]}'
The format of your first line of the command with an example endpoint would appear as follows curl https://docs-test-001.openai.azure.com/openai/deployments/{YOUR-DEPLOYMENT_NAME_HERE}/chat/completions?api-version=2023-05-15 \
If you encounter an error double check to make sure that you don't have a doubling of the /
at the separation between your endpoint and /openai/deployments
.
If you want to run this command in a normal Windows command prompt you would need to alter the text to remove the \
and line breaks.
Important
For production, use a secure way of storing and accessing your credentials like Azure Key Vault. For more information about credential security, see the Cognitive Services security article.
Output
{"id":"chatcmpl-6v7mkQj980V1yBec6ETrKPRqFjNw9",
"object":"chat.completion","created":1679072642,
"model":"gpt-35-turbo",
"usage":{"prompt_tokens":58,
"completion_tokens":68,
"total_tokens":126},
"choices":[{"message":{"role":"assistant",
"content":"Yes, other Azure Cognitive Services also support customer managed keys. Azure Cognitive Services offer multiple options for customers to manage keys, such as using Azure Key Vault, customer-managed keys in Azure Key Vault or customer-managed keys through Azure Storage service. This helps customers ensure that their data is secure and access to their services is controlled."},"finish_reason":"stop","index":0}]}
Output formatting adjusted for ease of reading, actual output is a single block of text without line breaks.
I ran into an issue when running the code sample.
Understanding the message structure
The GPT-35-Turbo and GPT-4 models are optimized to work with inputs formatted as a conversation. The messages
variable passes an array of dictionaries with different roles in the conversation delineated by system, user, and assistant. The system message can be used to prime the model by including context or instructions on how the model should respond.
The GPT-35-Turbo & GPT-4 how-to guide provides an in-depth introduction into the options for communicating with these new models.
Clean up resources
If you want to clean up and remove an OpenAI resource, you can delete the resource. Before deleting the resource, you must first delete any deployed models.
Portal
Azure CLI
Next steps
Learn more about how to work with GPT-35-Turbo and the GPT-4 models with our how-to guide.
For more examples, check out the Azure OpenAI Samples GitHub repository