Skip to content

Commit 82b57b4

Browse files
new assistants quickstart (#44536)
* new assistants quickstart --------- Co-authored-by: Genevieve Warren <[email protected]>
1 parent fba513c commit 82b57b4

File tree

5 files changed

+302
-0
lines changed

5 files changed

+302
-0
lines changed
71.4 KB
Loading
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
---
2+
title: Quickstart - Create a minimal AI assistant using .NET
3+
description: Learn to create a minimal AI assistant with tooling capabilities using .NET and the Azure OpenAI SDK libraries
4+
ms.date: 01/25/2025
5+
ms.topic: quickstart
6+
ms.custom: devx-track-dotnet, devx-track-dotnet-ai
7+
author: alexwolfmsft
8+
ms.author: alexwolf
9+
zone_pivot_groups: openai-library
10+
---
11+
12+
# Create a minimal AI assistant using .NET
13+
14+
In this quickstart, you'll learn how to create a minimal AI assistant using the OpenAI or Azure OpenAI SDK libraries. AI assistants provide agentic functionality to help users complete tasks using AI tools and models. In the sections ahead, you'll learn the following:
15+
16+
- Core components and concepts of AI assistants
17+
- How to create an assistant using the Azure OpenAI SDK
18+
- How to enhance and customize the capabilities of an assistant
19+
20+
## Prerequisites
21+
22+
::: zone pivot="openai"
23+
24+
* [Install .NET 8.0](https://dotnet.microsoft.com/download) or higher
25+
* [Visual Studio Code](https://code.visualstudio.com/) (optional)
26+
* [Visual Studio](https://visualstudio.com/) (optional)
27+
* An access key for an OpenAI model
28+
29+
:::zone-end
30+
31+
::: zone pivot="azure-openai"
32+
33+
* [Install .NET 8.0](https://dotnet.microsoft.com/download) or higher
34+
* [Visual Studio Code](https://code.visualstudio.com/) (optional)
35+
* [Visual Studio](https://visualstudio.com/) (optional)
36+
* Access to an Azure OpenAI instance via Azure Identity or an access key
37+
38+
:::zone-end
39+
40+
## Core components of AI assistants
41+
42+
AI assistants are based around conversational threads with a user. The user sends prompts to the assistant on a conversation thread, which directs the assistant to complete tasks using the tools it has available. Assistants can process and analyze data, make decisions, and interact with users or other systems to achieve specific goals. Most assistants include the following components:
43+
44+
| **Component** | **Description** |
45+
|---|---|
46+
| **Assistant** | The core AI client and logic that uses Azure OpenAI models, manages conversation threads, and utilizes configured tools. |
47+
| **Thread** | A conversation session between an assistant and a user. Threads store messages and automatically handle truncation to fit content into a model's context. |
48+
| **Message** | A message created by an assistant or a user. Messages can include text, images, and other files. Messages are stored as a list on the thread. |
49+
| **Run** | Activation of an assistant to begin running based on the contents of the thread. The assistant uses its configuration and the thread's messages to perform tasks by calling models and tools. As part of a run, the assistant appends messages to the thread. |
50+
| **Run steps** | A detailed list of steps the assistant took as part of a run. An assistant can call tools or create messages during its run. Examining run steps allows you to understand how the assistant is getting to its final results. |
51+
52+
Assistants can also be configured to use multiple tools in parallel to complete tasks, including the following:
53+
54+
- **Code interpreter tool**: Writes and runs code in a sandboxed execution environment.
55+
- **Function calling**: Runs local custom functions you define in your code.
56+
- **File search capabilities**: Augments the assistant with knowledge from outside its model.
57+
58+
By understanding these core components and how they interact, you can build and customize powerful AI assistants to meet your specific needs.
59+
60+
## Create the .NET app
61+
62+
Complete the following steps to create a .NET console app and add the package needed to work with assistants:
63+
64+
::: zone pivot="openai"
65+
66+
1. In a terminal window, navigate to an empty directory on your device and create a new app with the `dotnet new` command:
67+
68+
```dotnetcli
69+
dotnet new console -o AIAssistant
70+
```
71+
72+
1. Add the [OpenAI](https://www.nuget.org/packages/OpenAI) package to your app:
73+
74+
```dotnetcli
75+
dotnet add package OpenAI --prerelease
76+
```
77+
78+
1. Open the new app in your editor of choice, such as Visual Studio Code.
79+
80+
```dotnetcli
81+
code .
82+
```
83+
84+
::: zone-end
85+
86+
::: zone pivot="azure-openai"
87+
88+
1. In a terminal window, navigate to an empty directory on your device and create a new app with the `dotnet new` command:
89+
90+
```dotnetcli
91+
dotnet new console -o AIAssistant
92+
```
93+
94+
1. Add the [Azure.AI.OpenAI](https://www.nuget.org/packages/Azure.AI.OpenAI) package to your app:
95+
96+
```dotnetcli
97+
dotnet add package Azure.AI.OpenAI --prerelease
98+
```
99+
100+
1. Open the new app in your editor of choice, such as Visual Studio Code.
101+
102+
```dotnetcli
103+
code .
104+
```
105+
106+
::: zone-end
107+
108+
## Create the AI assistant client
109+
110+
1. Open the _Program.cs_ file and replace the contents of the file with the following code to create the required clients:
111+
112+
:::code language="csharp" source="snippets/assistants/program.cs" range="0-17" :::
113+
114+
1. Create an in-memory sample document and upload it to the `OpenAIFileClient`:
115+
116+
:::code language="csharp" source="snippets/assistants/program.cs" range="19-53" :::
117+
118+
1. Enable file search and code interpreter tooling capabilities via the `AssistantCreationOptions`:
119+
120+
:::code language="csharp" source="snippets/assistants/program.cs" range="55-78" :::
121+
122+
1. Create the `Assistant` and a thread to manage interactions between the user and the assistant:
123+
124+
:::code language="csharp" source="snippets/assistants/program.cs" range="80-105" :::
125+
126+
1. Print the messages and save the generated image from the conversation with the assistant:
127+
128+
:::code language="csharp" source="snippets/assistants/program.cs" range="107-147" :::
129+
130+
Locate and open the saved image in the app *bin* directory, which should resemble the following:
131+
132+
:::image type="content" source="../media/assistants/generated-sales-graph.png" alt-text="A graph showing the visualization generated by the AI model.":::
133+
134+
## Next steps
135+
136+
- [Quickstart - Get insight about your data from an .NET Azure AI chat app](../how-to/work-with-local-models.md)
137+
- [Generate text and conversations with .NET and Azure OpenAI Completions](/training/modules/open-ai-dotnet-text-completions/)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net9.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="Azure.AI.OpenAI" Version="2.1.0-beta.2" />
12+
<PackageReference Include="Azure.Identity" Version="1.13.1" />
13+
<PackageReference Include="OpenAI" Version="2.1.0" />
14+
</ItemGroup>
15+
16+
</Project>
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
using OpenAI;
2+
using OpenAI.Assistants;
3+
using OpenAI.Files;
4+
using Azure.AI.OpenAI;
5+
using Azure.Identity;
6+
7+
// Create the OpenAI client
8+
OpenAIClient openAIClient = new("your-apy-key");
9+
10+
// For Azure OpenAI, use the following client instead:
11+
AzureOpenAIClient azureAIClient = new(
12+
new Uri("your-azure-openai-endpoint"),
13+
new DefaultAzureCredential());
14+
15+
#pragma warning disable OPENAI001
16+
AssistantClient assistantClient = openAIClient.GetAssistantClient();
17+
OpenAIFileClient fileClient = openAIClient.GetOpenAIFileClient();
18+
19+
// Create an in-memory document to upload to the file client
20+
using Stream document = BinaryData.FromBytes("""
21+
{
22+
"description": "This document contains the sale history data for Contoso products.",
23+
"sales": [
24+
{
25+
"month": "January",
26+
"by_product": {
27+
"113043": 15,
28+
"113045": 12,
29+
"113049": 2
30+
}
31+
},
32+
{
33+
"month": "February",
34+
"by_product": {
35+
"113045": 22
36+
}
37+
},
38+
{
39+
"month": "March",
40+
"by_product": {
41+
"113045": 16,
42+
"113055": 5
43+
}
44+
}
45+
]
46+
}
47+
"""u8.ToArray()).ToStream();
48+
49+
// Upload the document to the file client
50+
OpenAIFile salesFile = fileClient.UploadFile(
51+
document,
52+
"monthly_sales.json",
53+
FileUploadPurpose.Assistants);
54+
55+
// Configure the assistant options
56+
AssistantCreationOptions assistantOptions = new()
57+
{
58+
Name = "Example: Contoso sales RAG",
59+
Instructions =
60+
"You are an assistant that looks up sales data and helps visualize the information based"
61+
+ " on user queries. When asked to generate a graph, chart, or other visualization, use"
62+
+ " the code interpreter tool to do so.",
63+
Tools =
64+
{
65+
new FileSearchToolDefinition(), // Enable the assistant to search and access files
66+
new CodeInterpreterToolDefinition(), // Enable the assistant to run code for data analysis
67+
},
68+
ToolResources = new()
69+
{
70+
FileSearch = new()
71+
{
72+
NewVectorStores =
73+
{
74+
new VectorStoreCreationHelper([salesFile.Id]),
75+
}
76+
}
77+
},
78+
};
79+
80+
// Create the assistant
81+
Assistant assistant = assistantClient.CreateAssistant("gpt-4o", assistantOptions);
82+
83+
// Configure and create the conversation thread
84+
ThreadCreationOptions threadOptions = new()
85+
{
86+
InitialMessages = { "How well did product 113045 sell in February? Graph its trend over time." }
87+
};
88+
89+
ThreadRun threadRun = assistantClient.CreateThreadAndRun(assistant.Id, threadOptions);
90+
91+
// Sent the prompt and monitor progress until the thread run is complete
92+
do
93+
{
94+
Thread.Sleep(TimeSpan.FromSeconds(1));
95+
threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
96+
}
97+
while (!threadRun.Status.IsTerminal);
98+
99+
// Get the messages from the thread run
100+
var messages = assistantClient.GetMessagesAsync(
101+
threadRun.ThreadId,
102+
new MessageCollectionOptions()
103+
{
104+
Order = MessageCollectionOrder.Ascending
105+
});
106+
107+
await foreach (ThreadMessage message in messages)
108+
{
109+
// Print out the messages from the assistant
110+
Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
111+
foreach (MessageContent contentItem in message.Content)
112+
{
113+
if (!string.IsNullOrEmpty(contentItem.Text))
114+
{
115+
Console.WriteLine($"{contentItem.Text}");
116+
117+
if (contentItem.TextAnnotations.Count > 0)
118+
{
119+
Console.WriteLine();
120+
}
121+
122+
// Include annotations, if any
123+
foreach (TextAnnotation annotation in contentItem.TextAnnotations)
124+
{
125+
if (!string.IsNullOrEmpty(annotation.InputFileId))
126+
{
127+
Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}");
128+
}
129+
if (!string.IsNullOrEmpty(annotation.OutputFileId))
130+
{
131+
Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}");
132+
}
133+
}
134+
}
135+
// Save the generated image file
136+
if (!string.IsNullOrEmpty(contentItem.ImageFileId))
137+
{
138+
OpenAIFile imageInfo = fileClient.GetFile(contentItem.ImageFileId);
139+
BinaryData imageBytes = fileClient.DownloadFile(contentItem.ImageFileId);
140+
using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
141+
imageBytes.ToStream().CopyTo(stream);
142+
143+
Console.WriteLine($"<image: {imageInfo.Filename}.png>");
144+
}
145+
}
146+
Console.WriteLine();
147+
}

docs/ai/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ items:
2727
href: quickstarts/quickstart-openai-generate-images.md
2828
- name: Chat with a local AI model
2929
href: quickstarts/quickstart-local-ai.md
30+
- name: Build a minimal AI assistant
31+
href: quickstarts/quickstart-assistants.md
3032
- name: Concepts
3133
items:
3234
- name: How generative AI and LLMs work

0 commit comments

Comments
 (0)