Skip to content

Commit 2cf8d64

Browse files
authored
Merge pull request #3428 from eric-urban/eur/aoai-managed-identity
Entra ID for AOAI QS - C#
2 parents 2e487ac + 272a9e6 commit 2cf8d64

File tree

11 files changed

+432
-409
lines changed

11 files changed

+432
-409
lines changed

articles/ai-services/openai/assistants-quickstart.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ ms.custom: devx-track-python, devx-track-dotnet, devx-track-extended-java, devx-
88
ms.topic: quickstart
99
author: aahill
1010
ms.author: aahi
11-
ms.date: 02/10/2025
11+
ms.date: 3/10/2025
1212
zone_pivot_groups: openai-quickstart-assistants
1313
recommendations: false
1414
---

articles/ai-services/openai/how-to/dotnet-migration.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,10 @@ OpenAIClient client = new(
4848

4949
```csharp
5050
// 2.0 - NEW: Get a chat completions client from a top-level Azure client
51-
AzureOpenAIClient azureClient = new(
51+
AzureOpenAIClient openAIClient = new(
5252
new Uri("https://your-resource.openai.azure.com/"),
5353
new AzureKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY"));
54-
ChatClient chatClient = azureClient.GetChatClient("my-gpt-4o-mini-deployment");
54+
ChatClient chatClient = openAIClient.GetChatClient("my-gpt-4o-mini-deployment");
5555
```
5656

5757
Just like in 1.0, the new `AzureOpenAIClient` supports the use of Microsoft Entra ID credentials when the [Azure.Identity](/dotnet/api/overview/azure/identity-readme?view=azure-dotnet&preserve-view=true) package is installed.

articles/ai-services/openai/includes/assistants-csharp.md

Lines changed: 269 additions & 277 deletions
Large diffs are not rendered by default.

articles/ai-services/openai/includes/chatgpt-dotnet.md

Lines changed: 137 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -16,103 +16,175 @@ ms.date: 11/15/2023
1616

1717
- An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services?azure-portal=true)
1818
- The [.NET 7 SDK](https://dotnet.microsoft.com/download/dotnet/7.0)
19-
- An Azure OpenAI Service resource with either the `gpt-35-turbo` or the `gpt-4` models deployed. For more information about model deployment, see the [resource deployment guide](../how-to/create-resource.md).
19+
- An Azure OpenAI Service resource with the `gpt-4o` model deployed. For more information about model deployment, see the [resource deployment guide](../how-to/create-resource.md).
2020

21+
### Microsoft Entra ID prerequisites
22+
23+
For the recommended keyless authentication with Microsoft Entra ID, you need to:
24+
- Install the [Azure CLI](/cli/azure/install-azure-cli) used for keyless authentication with Microsoft Entra ID.
25+
- Assign the `Cognitive Services User` role to your user account. You can assign roles in the Azure portal under **Access control (IAM)** > **Add role assignment**.
2126

2227
## Set up
2328

24-
[!INCLUDE [Create a new .NET application](./dotnet-new-application.md)]
29+
1. Create a new folder `chat-quickstart` to contain the application and open Visual Studio Code in that folder with the following command:
2530

26-
[!INCLUDE [get-key-endpoint](get-key-endpoint.md)]
31+
```shell
32+
mkdir chat-quickstart && cd chat-quickstart
33+
```
2734

28-
[!INCLUDE [environment-variables](environment-variables.md)]
35+
1. Create a new console application with the following command:
2936

37+
```shell
38+
dotnet new console
39+
```
3040

31-
## Create a sample application
41+
3. Install the [OpenAI .NET client library](https://www.nuget.org/packages/Azure.AI.OpenAI/) with the [dotnet add package](/dotnet/core/tools/dotnet-add-package) command:
3242

33-
From the project directory, open the *program.cs* file and replace with the following code:
43+
```console
44+
dotnet add package Azure.AI.OpenAI --prerelease
45+
```
3446

35-
### Without response streaming
47+
1. For the **recommended** keyless authentication with Microsoft Entra ID, install the [Azure.Identity](https://www.nuget.org/packages/Azure.Identity) package with:
3648

37-
```csharp
38-
using Azure;
39-
using Azure.AI.OpenAI;
40-
using static System.Environment;
49+
```console
50+
dotnet add package Azure.Identity
51+
```
52+
53+
1. For the **recommended** keyless authentication with Microsoft Entra ID, sign in to Azure with the following command:
54+
55+
```console
56+
az login
57+
```
4158

42-
string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
43-
string key = GetEnvironmentVariable("AZURE_OPENAI_API_KEY");
59+
## Retrieve resource information
4460

45-
AzureOpenAIClient azureClient = new(
46-
new Uri(endpoint),
47-
new AzureKeyCredential(key));
61+
[!INCLUDE [resource authentication](resource-authentication.md)]
4862

49-
// This must match the custom deployment name you chose for your model
50-
ChatClient chatClient = azureClient.GetChatClient("gpt-35-turbo");
63+
## Add the code for chat completion
5164

52-
ChatCompletion completion = chatClient.CompleteChat(
53-
[
54-
new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
55-
new UserChatMessage("Does Azure OpenAI support customer managed keys?"),
56-
new AssistantChatMessage("Yes, customer managed keys are supported by Azure OpenAI"),
57-
new UserChatMessage("Do other Azure AI services support this too?")
58-
]);
65+
The sample code in this quickstart uses Microsoft Entra ID for the recommended keyless authentication. If you prefer to use an API key, you can replace the `DefaultAzureCredential` object with a `AzureKeyCredential` object.
5966

60-
Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");
67+
#### [Microsoft Entra ID](#tab/keyless)
68+
69+
```csharp
70+
AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential());
6171
```
6272
63-
> [!IMPORTANT]
64-
> For production, use a secure way of storing and accessing your credentials like [Azure Key Vault](/azure/key-vault/general/overview). For more information about credential security, see the Azure AI services [security](../../security-features.md) article.
73+
#### [API key](#tab/api-key)
6574
66-
```cmd
67-
dotnet run program.cs
75+
```csharp
76+
AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));
6877
```
78+
---
79+
80+
You can use streaming or non-streaming to get the chat completion. The following code examples show how to use both methods. The first example shows how to use the non-streaming method, and the second example shows how to use the streaming method.
6981
70-
## Output
82+
### Without response streaming
83+
84+
To use the non-streaming method:
85+
86+
1. Update the `Program.cs` file with the following code:
87+
88+
```csharp
89+
using Azure;
90+
using Azure.Identity;
91+
using OpenAI.Assistants;
92+
using Azure.AI.OpenAI;
93+
using OpenAI.Chat;
94+
using static System.Environment;
95+
96+
string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? "https://<your-resource-name>.openai.azure.com/";
97+
string key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? "<your-key>";
98+
99+
// Use the recommended keyless credential instead of the AzureKeyCredential credential.
100+
AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential());
101+
//AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));
102+
103+
// This must match the custom deployment name you chose for your model
104+
ChatClient chatClient = openAIClient.GetChatClient("gpt-4o");
105+
106+
ChatCompletion completion = chatClient.CompleteChat(
107+
[
108+
new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
109+
new UserChatMessage("Does Azure OpenAI support customer managed keys?"),
110+
new AssistantChatMessage("Yes, customer managed keys are supported by Azure OpenAI"),
111+
new UserChatMessage("Do other Azure AI services support this too?")
112+
]);
113+
114+
Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");
115+
```
116+
117+
1. Run the application with the following command:
118+
119+
```shell
120+
dotnet run
121+
```
122+
123+
124+
#### Output
71125
72126
```output
73-
Assistant : Yes, many other Azure AI services also support customer managed keys, including Azure Cognitive Services, Azure Machine Learning, and Azure Databricks. By using customer managed keys, you can retain complete control over your encryption keys and provide an additional layer of security for your AI assets.
127+
Assistant: Arrr, ye be askin’ a fine question, matey! Aye, several Azure AI services support customer-managed keys (CMK)! This lets ye take the wheel and secure yer data with encryption keys stored in Azure Key Vault. Services such as Azure Machine Learning, Azure Cognitive Search, and others also offer CMK fer data protection. Always check the specific service's documentation fer the latest updates, as features tend to shift swifter than the tides, aye!
74128
```
75129
76130
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.
77131
78132
### Async with streaming
79133
80-
```csharp
81-
using Azure;
82-
using Azure.AI.OpenAI;
83-
using OpenAI.Chat;
84-
using static System.Environment;
85-
86-
string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
87-
string key = GetEnvironmentVariable("AZURE_OPENAI_API_KEY");
88-
89-
AzureOpenAIClient azureClient = new(
90-
new Uri(endpoint),
91-
new AzureKeyCredential(key));
92-
93-
// This must match the custom deployment name you chose for your model
94-
ChatClient chatClient = azureClient.GetChatClient("gpt-35-turbo");
95-
96-
var chatUpdates = chatClient.CompleteChatStreamingAsync(
97-
[
98-
new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
99-
new UserChatMessage("Does Azure OpenAI support customer managed keys?"),
100-
new AssistantChatMessage("Yes, customer managed keys are supported by Azure OpenAI"),
101-
new UserChatMessage("Do other Azure AI services support this too?")
102-
]);
103-
104-
await foreach(var chatUpdate in chatUpdates)
105-
{
106-
if (chatUpdate.Role.HasValue)
107-
{
108-
Console.Write($"{chatUpdate.Role} : ");
109-
}
134+
To use the streaming method:
135+
1. Update the `Program.cs` file with the following code:
136+
137+
```csharp
138+
using Azure;
139+
using Azure.Identity;
140+
using OpenAI.Assistants;
141+
using Azure.AI.OpenAI;
142+
using OpenAI.Chat;
143+
using static System.Environment;
144+
145+
string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? "https://<your-resource-name>.openai.azure.com/";
146+
string key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? "<your-key>";
110147
111-
foreach(var contentPart in chatUpdate.ContentUpdate)
148+
// Use the recommended keyless credential instead of the AzureKeyCredential credential.
149+
AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential());
150+
//AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));
151+
152+
// This must match the custom deployment name you chose for your model
153+
ChatClient chatClient = openAIClient.GetChatClient("gpt-4o");
154+
155+
var chatUpdates = chatClient.CompleteChatStreamingAsync(
156+
[
157+
new SystemChatMessage("You are a helpful assistant that talks like a pirate."),
158+
new UserChatMessage("Does Azure OpenAI support customer managed keys?"),
159+
new AssistantChatMessage("Yes, customer managed keys are supported by Azure OpenAI"),
160+
new UserChatMessage("Do other Azure AI services support this too?")
161+
]);
162+
163+
await foreach(var chatUpdate in chatUpdates)
112164
{
113-
Console.Write(contentPart.Text);
165+
if (chatUpdate.Role.HasValue)
166+
{
167+
Console.Write($"{chatUpdate.Role} : ");
168+
}
169+
170+
foreach(var contentPart in chatUpdate.ContentUpdate)
171+
{
172+
Console.Write(contentPart.Text);
173+
}
114174
}
115-
}
175+
```
176+
177+
1. Run the application with the following command:
178+
179+
```shell
180+
dotnet run
181+
```
182+
183+
184+
#### Output
185+
186+
```output
187+
Assistant: Arrr, ye be askin’ a fine question, matey! Aye, several Azure AI services support customer-managed keys (CMK)! This lets ye take the wheel and secure yer data with encryption keys stored in Azure Key Vault. Services such as Azure Machine Learning, Azure Cognitive Search, and others also offer CMK fer data protection. Always check the specific service's documentation fer the latest updates, as features tend to shift swifter than the tides, aye!
116188
```
117189
118190

articles/ai-services/openai/includes/dall-e-dotnet.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,12 @@ using static System.Environment;
7474
string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
7575
string key = GetEnvironmentVariable("AZURE_OPENAI_API_KEY");
7676

77-
AzureOpenAIClient azureClient = new(
77+
AzureOpenAIClient openAIClient = new(
7878
new Uri(endpoint),
7979
new AzureKeyCredential(key));
8080

8181
// This must match the custom deployment name you chose for your model
82-
ImageClient chatClient = azureClient.GetImageClient("dalle-3");
82+
ImageClient chatClient = openAIClient.GetImageClient("dalle-3");
8383

8484
var imageGeneration = await chatClient.GenerateImageAsync(
8585
"a happy monkey sitting in a tree, in watercolor",

articles/ai-services/openai/includes/dotnet-new-application.md

Lines changed: 0 additions & 39 deletions
This file was deleted.

articles/ai-services/openai/includes/gpt-v-dotnet.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ Passwordless authentication is more secure than key-based alternatives and is th
8484
// var credentials = new DefaultAzureCredential(); // Use this line for Passwordless auth
8585
var deploymentName = "gpt-4"; // Default name, update with your own if needed
8686
87-
var openAIClient = new AzureOpenAIClient(endpoint, credentials);
87+
AzureOpenAIClient openAIClient = new AzureOpenAIClient(endpoint, credentials);
8888
var chatClient = openAIClient.GetChatClient(deploymentName);
8989
9090
var imageUri = "YOUR_IMAGE_URL";

0 commit comments

Comments
 (0)