openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.1.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/Assistants/Example01_RetrievalAugmentedGenerationAsync.cs

149lines · modeblame

9f9f2936Jose Arriaga Maldonado2 years ago1using NUnit.Framework;
2using OpenAI.Assistants;
3using OpenAI.Files;
4using System;
5using System.ClientModel;
6using System.IO;
7using System.Threading;
8using System.Threading.Tasks;
9
8cc6643fJose Arriaga Maldonado2 years ago10namespace OpenAI.Examples;
9f9f2936Jose Arriaga Maldonado2 years ago11
8cc6643fJose Arriaga Maldonado2 years ago12public partial class AssistantExamples
9f9f2936Jose Arriaga Maldonado2 years ago13{
14[Test]
8cc6643fJose Arriaga Maldonado2 years ago15public async Task Example01_RetrievalAugmentedGenerationAsync()
9f9f2936Jose Arriaga Maldonado2 years ago16{
17// Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning.
a330c2e7Jose Arriaga Maldonado1 years ago18#pragma warning disable OPENAI001
9f9f2936Jose Arriaga Maldonado2 years ago19OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
31c2ba63Jose Arriaga Maldonado1 years ago20OpenAIFileClient fileClient = openAIClient.GetOpenAIFileClient();
9f9f2936Jose Arriaga Maldonado2 years ago21AssistantClient assistantClient = openAIClient.GetAssistantClient();
22
23// First, let's contrive a document we'll use retrieval with and upload it.
e4af1691Jose Arriaga Maldonado1 years ago24using Stream document = BinaryData.FromBytes("""
9f9f2936Jose Arriaga Maldonado2 years ago25{
26"description": "This document contains the sale history data for Contoso products.",
27"sales": [
28{
29"month": "January",
30"by_product": {
31"113043": 15,
32"113045": 12,
33"113049": 2
34}
35},
36{
37"month": "February",
38"by_product": {
39"113045": 22
40}
41},
42{
43"month": "March",
44"by_product": {
45"113045": 16,
46"113055": 5
47}
48}
49]
50}
e4af1691Jose Arriaga Maldonado1 years ago51"""u8.ToArray()).ToStream();
9f9f2936Jose Arriaga Maldonado2 years ago52
19ceae44ShivangiReja1 years ago53OpenAIFile salesFile = await fileClient.UploadFileAsync(
9f9f2936Jose Arriaga Maldonado2 years ago54document,
55"monthly_sales.json",
56FileUploadPurpose.Assistants);
57
58// Now, we'll create a client intended to help with that data
59AssistantCreationOptions assistantOptions = new()
60{
61Name = "Example: Contoso sales RAG",
62Instructions =
63"You are an assistant that looks up sales data and helps visualize the information based"
64+ " on user queries. When asked to generate a graph, chart, or other visualization, use"
65+ " the code interpreter tool to do so.",
66Tools =
67{
68new FileSearchToolDefinition(),
69new CodeInterpreterToolDefinition(),
70},
71ToolResources = new()
72{
73FileSearch = new()
74{
75NewVectorStores =
76{
77new VectorStoreCreationHelper([salesFile.Id]),
78}
79}
80},
81};
82
83Assistant assistant = await assistantClient.CreateAssistantAsync("gpt-4o", assistantOptions);
84
85// Now we'll create a thread with a user query about the data already associated with the assistant, then run it
86ThreadCreationOptions threadOptions = new()
87{
d665b61fTravis Wilson2 years ago88InitialMessages = { "How well did product 113045 sell in February? Graph its trend over time." }
9f9f2936Jose Arriaga Maldonado2 years ago89};
90
91ThreadRun threadRun = await assistantClient.CreateThreadAndRunAsync(assistant.Id, threadOptions);
92
93// Check back to see when the run is done
94do
95{
96Thread.Sleep(TimeSpan.FromSeconds(1));
97threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
98} while (!threadRun.Status.IsTerminal);
99
100// Finally, we'll print out the full history for the thread that includes the augmented generation
2ab1a942Jose Arriaga Maldonado1 years ago101AsyncCollectionResult<ThreadMessage> messages
102= assistantClient.GetMessagesAsync(threadRun.ThreadId, new MessageCollectionOptions() { Order = MessageCollectionOrder.Ascending });
b0f9e5c3Jose Arriaga Maldonado1 years ago103
9f9f2936Jose Arriaga Maldonado2 years ago104await foreach (ThreadMessage message in messages)
105{
106Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
107foreach (MessageContent contentItem in message.Content)
108{
109if (!string.IsNullOrEmpty(contentItem.Text))
110{
111Console.WriteLine($"{contentItem.Text}");
112
113if (contentItem.TextAnnotations.Count > 0)
114{
115Console.WriteLine();
116}
117
118// Include annotations, if any.
119foreach (TextAnnotation annotation in contentItem.TextAnnotations)
120{
121if (!string.IsNullOrEmpty(annotation.InputFileId))
122{
123Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}");
124}
125if (!string.IsNullOrEmpty(annotation.OutputFileId))
126{
127Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}");
128}
129}
130}
131if (!string.IsNullOrEmpty(contentItem.ImageFileId))
132{
19ceae44ShivangiReja1 years ago133OpenAIFile imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId);
9f9f2936Jose Arriaga Maldonado2 years ago134BinaryData imageBytes = await fileClient.DownloadFileAsync(contentItem.ImageFileId);
135using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
136imageBytes.ToStream().CopyTo(stream);
137
138Console.WriteLine($"<image: {imageInfo.Filename}.png>");
139}
140}
141Console.WriteLine();
142}
143
144// Optionally, delete any persistent resources you no longer need.
145_ = await assistantClient.DeleteThreadAsync(threadRun.ThreadId);
a330c2e7Jose Arriaga Maldonado1 years ago146_ = await assistantClient.DeleteAssistantAsync(assistant.Id);
13a9c686Jose Arriaga Maldonado2 years ago147_ = await fileClient.DeleteFileAsync(salesFile.Id);
9f9f2936Jose Arriaga Maldonado2 years ago148}
149}