openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.1.0-beta.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/Assistants/Example01_RetrievalAugmentedGenerationAsync.cs

149lines · modecode

1using NUnit.Framework;
2using OpenAI.Assistants;
3using OpenAI.Files;
4using System;
5using System.ClientModel;
6using System.IO;
7using System.Threading;
8using System.Threading.Tasks;
9
10namespace OpenAI.Examples;
11
12public partial class AssistantExamples
13{
14 [Test]
15 public async Task Example01_RetrievalAugmentedGenerationAsync()
16 {
17 // Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning.
18 #pragma warning disable OPENAI001
19 OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
20 OpenAIFileClient fileClient = openAIClient.GetOpenAIFileClient();
21 AssistantClient assistantClient = openAIClient.GetAssistantClient();
22
23 // First, let's contrive a document we'll use retrieval with and upload it.
24 using Stream document = BinaryData.FromBytes("""
25 {
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 }
51 """u8.ToArray()).ToStream();
52
53 OpenAIFile salesFile = await fileClient.UploadFileAsync(
54 document,
55 "monthly_sales.json",
56 FileUploadPurpose.Assistants);
57
58 // Now, we'll create a client intended to help with that data
59 AssistantCreationOptions assistantOptions = new()
60 {
61 Name = "Example: Contoso sales RAG",
62 Instructions =
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.",
66 Tools =
67 {
68 new FileSearchToolDefinition(),
69 new CodeInterpreterToolDefinition(),
70 },
71 ToolResources = new()
72 {
73 FileSearch = new()
74 {
75 NewVectorStores =
76 {
77 new VectorStoreCreationHelper([salesFile.Id]),
78 }
79 }
80 },
81 };
82
83 Assistant 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
86 ThreadCreationOptions threadOptions = new()
87 {
88 InitialMessages = { "How well did product 113045 sell in February? Graph its trend over time." }
89 };
90
91 ThreadRun threadRun = await assistantClient.CreateThreadAndRunAsync(assistant.Id, threadOptions);
92
93 // Check back to see when the run is done
94 do
95 {
96 Thread.Sleep(TimeSpan.FromSeconds(1));
97 threadRun = 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
101 AsyncCollectionResult<ThreadMessage> messages
102 = assistantClient.GetMessagesAsync(threadRun.ThreadId, new MessageCollectionOptions() { Order = MessageCollectionOrder.Ascending });
103
104 await foreach (ThreadMessage message in messages)
105 {
106 Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
107 foreach (MessageContent contentItem in message.Content)
108 {
109 if (!string.IsNullOrEmpty(contentItem.Text))
110 {
111 Console.WriteLine($"{contentItem.Text}");
112
113 if (contentItem.TextAnnotations.Count > 0)
114 {
115 Console.WriteLine();
116 }
117
118 // Include annotations, if any.
119 foreach (TextAnnotation annotation in contentItem.TextAnnotations)
120 {
121 if (!string.IsNullOrEmpty(annotation.InputFileId))
122 {
123 Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}");
124 }
125 if (!string.IsNullOrEmpty(annotation.OutputFileId))
126 {
127 Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}");
128 }
129 }
130 }
131 if (!string.IsNullOrEmpty(contentItem.ImageFileId))
132 {
133 OpenAIFile imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId);
134 BinaryData imageBytes = await fileClient.DownloadFileAsync(contentItem.ImageFileId);
135 using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
136 imageBytes.ToStream().CopyTo(stream);
137
138 Console.WriteLine($"<image: {imageInfo.Filename}.png>");
139 }
140 }
141 Console.WriteLine();
142 }
143
144 // Optionally, delete any persistent resources you no longer need.
145 _ = await assistantClient.DeleteThreadAsync(threadRun.ThreadId);
146 _ = await assistantClient.DeleteAssistantAsync(assistant.Id);
147 _ = await fileClient.DeleteFileAsync(salesFile.Id);
148 }
149}
150