Skip to content

Commit 8664ec3

Browse files
authored
Merge pull request #268054 from aaronpowell/oai-assistants-dotnet-quickstart
Adding a C# assistants to the quickstarts
2 parents dd47aa0 + bce2899 commit 8664ec3

File tree

3 files changed

+180
-1
lines changed

3 files changed

+180
-1
lines changed

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ ms.topic: quickstart
99
author: mrbullwinkle
1010
ms.author: mbullwin
1111
ms.date: 02/01/2024
12-
zone_pivot_groups: openai-quickstart
12+
zone_pivot_groups: openai-quickstart-assistants
1313
recommendations: false
1414
---
1515

@@ -30,6 +30,12 @@ Azure OpenAI Assistants (Preview) allows you to create AI assistants tailored to
3030

3131
::: zone-end
3232

33+
::: zone pivot="programming-language-csharp"
34+
35+
[!INCLUDE [C# quickstart](includes/assistants-csharp.md)]
36+
37+
::: zone-end
38+
3339
::: zone pivot="rest-api"
3440

3541
[!INCLUDE [REST API quickstart](includes/assistants-rest.md)]
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
---
2+
title: 'Quickstart: Use the OpenAI Service via the .NET SDK'
3+
titleSuffix: Azure OpenAI Service
4+
description: Walkthrough on how to get started with Azure OpenAI and make your first completions call with the .NET SDK.
5+
manager: masoucou
6+
author: aapowell
7+
ms.author: aapowell
8+
ms.service: azure-ai-openai
9+
ms.topic: include
10+
ms.date: 03/05/2024
11+
---
12+
13+
[Source code](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/openai/Azure.AI.OpenAI/src) | [Package (NuGet)](https://www.nuget.org/packages/Azure.AI.OpenAI/)
14+
15+
## Prerequisites
16+
17+
- An Azure subscription - <a href="https://azure.microsoft.com/free/cognitive-services" target="_blank">Create one for free</a>
18+
- Access granted to Azure OpenAI in the desired Azure subscription
19+
20+
Currently, access to this service is granted only by application. You can apply for access to Azure OpenAI by completing the form at <a href="https://aka.ms/oai/access" target="_blank">https://aka.ms/oai/access</a>. Open an issue on this repo to contact us if you have an issue.
21+
- The [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)
22+
- Azure OpenAI Assistants are currently available in Sweden Central, East US 2, and Australia East. For more information about model availability in those regions, see the [models guide](../concepts/models.md).
23+
- We recommend reviewing the [Responsible AI transparency note](/legal/cognitive-services/openai/transparency-note?context=%2Fazure%2Fai-services%2Fopenai%2Fcontext%2Fcontext&tabs=text) and other [Responsible AI resources](/legal/cognitive-services/openai/overview?context=%2Fazure%2Fai-services%2Fopenai%2Fcontext%2Fcontext) to familiarize yourself with the capabilities and limitations of the Azure OpenAI Service.
24+
- An Azure OpenAI resource with the `gpt-4 (1106-preview)` model deployed was used testing this example.
25+
26+
## Set up
27+
28+
### Create a new .NET Core application
29+
30+
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*.
31+
32+
```dotnetcli
33+
dotnet new console -n azure-openai-assistants-quickstart
34+
```
35+
36+
Change your directory to the newly created app folder. You can build the application with:
37+
38+
```dotnetcli
39+
dotnet build
40+
```
41+
42+
The build output should contain no warnings or errors.
43+
44+
```output
45+
...
46+
Build succeeded.
47+
0 Warning(s)
48+
0 Error(s)
49+
...
50+
```
51+
52+
Install the OpenAI .NET client library with:
53+
54+
```console
55+
dotnet add package Azure.AI.OpenAI.Assistants --prerelease
56+
```
57+
58+
[!INCLUDE [get-key-endpoint](get-key-endpoint.md)]
59+
60+
[!INCLUDE [environment-variables](environment-variables.md)]
61+
62+
## Create an assistant
63+
64+
In our code we are going to specify the following values:
65+
66+
| **Name** | **Description** |
67+
|:---|:---|
68+
| **Assistant name** | Your deployment name that is associated with a specific model. |
69+
| **Instructions** | Instructions are similar to system messages this is where you give the model guidance about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality, tell it what it should and shouldn't answer, and tell it how to format responses. You can also provide examples of the steps it should take when answering responses. |
70+
| **Model** | This is where you set which model deployment name to use with your assistant. The retrieval tool requires `gpt-35-turbo (1106)` or `gpt-4 (1106-preview)` model. **Set this value to your deployment name, not the model name unless it is the same.** |
71+
| **Code interpreter** | Code interpreter provides access to a sandboxed Python environment that can be used to allow the model to test and execute code. |
72+
73+
### Tools
74+
75+
An individual assistant can access up to 128 tools including `code interpreter`, as well as any custom tools you create via [functions](../how-to/assistant-functions.md).
76+
77+
Create and run an assistant with the following:
78+
79+
```csharp
80+
using Azure;
81+
using Azure.AI.OpenAI.Assistants;
82+
83+
string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new ArgumentNullException("AZURE_OPENAI_ENDPOINT");
84+
string key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? throw new ArgumentNullException("AZURE_OPENAI_API_KEY");
85+
AssistantsClient client = new AssistantsClient(new Uri(endpoint), new AzureKeyCredential(key));
86+
87+
// Create an assistant
88+
Assistant assistant = await client.CreateAssistantAsync(
89+
new AssistantCreationOptions("gpt-4-1106-preview") // Replace this with the name of your model deployment
90+
{
91+
Name = "Math Tutor",
92+
Instructions = "You are a personal math tutor. Write and run code to answer math questions.",
93+
Tools = { new CodeInterpreterToolDefinition() }
94+
});
95+
96+
// Create a thread
97+
AssistantThread thread = await client.CreateThreadAsync();
98+
99+
// Add a user question to the thread
100+
ThreadMessage message = await client.CreateMessageAsync(
101+
thread.Id,
102+
MessageRole.User,
103+
"I need to solve the equation `3x + 11 = 14`. Can you help me?");
104+
105+
// Run the thread
106+
ThreadRun run = await client.CreateRunAsync(
107+
thread.Id,
108+
new CreateRunOptions(assistant.Id)
109+
);
110+
111+
// Wait for the assistant to respond
112+
do
113+
{
114+
await Task.Delay(TimeSpan.FromMilliseconds(500));
115+
run = await client.GetRunAsync(thread.Id, run.Id);
116+
}
117+
while (run.Status == RunStatus.Queued
118+
|| run.Status == RunStatus.InProgress);
119+
120+
// Get the messages
121+
PageableList<ThreadMessage> messagesPage = await client.GetMessagesAsync(thread.Id);
122+
IReadOnlyList<ThreadMessage> messages = messagesPage.Data;
123+
124+
// Note: messages iterate from newest to oldest, with the messages[0] being the most recent
125+
foreach (ThreadMessage threadMessage in messages.Reverse())
126+
{
127+
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
128+
foreach (MessageContent contentItem in threadMessage.ContentItems)
129+
{
130+
if (contentItem is MessageTextContent textItem)
131+
{
132+
Console.Write(textItem.Text);
133+
}
134+
Console.WriteLine();
135+
}
136+
}
137+
```
138+
139+
This will print an output as follows:
140+
141+
```
142+
2024-03-05 03:38:17 - user: I need to solve the equation `3x + 11 = 14`. Can you help me?
143+
2024-03-05 03:38:25 - assistant: The solution to the equation \(3x + 11 = 14\) is \(x = 1\).
144+
```
145+
146+
New messages can be created on the thread before re-running, which will see the assistant use the past messages as context within the thread.
147+
148+
## Clean up resources
149+
150+
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.
151+
152+
- [Portal](../../multi-service-resource.md?pivots=azportal#clean-up-resources)
153+
- [Azure CLI](../../multi-service-resource.md?pivots=azcli#clean-up-resources)
154+
155+
## See also
156+
157+
* Learn more about how to use Assistants with our [How-to guide on Assistants](../how-to/assistant.md).
158+
* [Azure OpenAI Assistants API samples](https://github.com/Azure-Samples/azureai-samples/tree/main/scenarios/Assistants)

articles/zone-pivot-groups.yml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1888,6 +1888,21 @@ groups:
18881888
title: Studio
18891889
- id: programming-language-python
18901890
title: Python
1891+
- id: programming-language-csharp
1892+
title: C#
1893+
- id: rest-api
1894+
title: REST
1895+
# Owner: mbullwin
1896+
- id: openai-quickstart-assistants
1897+
title: Programming languages
1898+
prompt: Choose your preferred usage method
1899+
pivots:
1900+
- id: programming-language-studio
1901+
title: Azure OpenAI Studio
1902+
- id: programming-language-python
1903+
title: Python
1904+
- id: programming-language-csharp
1905+
title: C#
18911906
- id: rest-api
18921907
title: REST
18931908
# Owner: mbullwin

0 commit comments

Comments
 (0)