openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.6.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/Assistants/Example01_RetrievalAugmentedGenerationAsync.cs

153lines · 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
12// This example uses experimental APIs which are subject to change. To use experimental APIs,
13// please acknowledge their experimental status by suppressing the corresponding warning.
14#pragma warning disable OPENAI001
15
16public partial class AssistantExamples
17{
18 [Test]
19 public async Task Example01_RetrievalAugmentedGenerationAsync()
20 {
21 OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
22 OpenAIFileClient fileClient = openAIClient.GetOpenAIFileClient();
23 AssistantClient assistantClient = openAIClient.GetAssistantClient();
24
25 // First, let's contrive a document we'll use retrieval with and upload it.
26 using Stream document = BinaryData.FromBytes("""
27 {
28 "description": "This document contains the sale history data for Contoso products.",
29 "sales": [
30 {
31 "month": "January",
32 "by_product": {
33 "113043": 15,
34 "113045": 12,
35 "113049": 2
36 }
37 },
38 {
39 "month": "February",
40 "by_product": {
41 "113045": 22
42 }
43 },
44 {
45 "month": "March",
46 "by_product": {
47 "113045": 16,
48 "113055": 5
49 }
50 }
51 ]
52 }
53 """u8.ToArray()).ToStream();
54
55 OpenAIFile salesFile = await fileClient.UploadFileAsync(
56 document,
57 "monthly_sales.json",
58 FileUploadPurpose.Assistants);
59
60 // Now, we'll create a client intended to help with that data
61 AssistantCreationOptions assistantOptions = new()
62 {
63 Name = "Example: Contoso sales RAG",
64 Instructions =
65 "You are an assistant that looks up sales data and helps visualize the information based"
66 + " on user queries. When asked to generate a graph, chart, or other visualization, use"
67 + " the code interpreter tool to do so.",
68 Tools =
69 {
70 new FileSearchToolDefinition(),
71 new CodeInterpreterToolDefinition(),
72 },
73 ToolResources = new()
74 {
75 FileSearch = new()
76 {
77 NewVectorStores =
78 {
79 new VectorStoreCreationHelper([salesFile.Id]),
80 }
81 }
82 },
83 };
84
85 Assistant assistant = await assistantClient.CreateAssistantAsync("gpt-4o", assistantOptions);
86
87 // Now we'll create a thread with a user query about the data already associated with the assistant, then run it
88 ThreadCreationOptions threadOptions = new()
89 {
90 InitialMessages = { "How well did product 113045 sell in February? Graph its trend over time." }
91 };
92
93 ThreadRun threadRun = await assistantClient.CreateThreadAndRunAsync(assistant.Id, threadOptions);
94
95 // Check back to see when the run is done
96 do
97 {
98 Thread.Sleep(TimeSpan.FromSeconds(1));
99 threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
100 } while (!threadRun.Status.IsTerminal);
101
102 // Finally, we'll print out the full history for the thread that includes the augmented generation
103 AsyncCollectionResult<ThreadMessage> messages
104 = assistantClient.GetMessagesAsync(threadRun.ThreadId, new MessageCollectionOptions() { Order = MessageCollectionOrder.Ascending });
105
106 await foreach (ThreadMessage message in messages)
107 {
108 Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
109 foreach (MessageContent contentItem in message.Content)
110 {
111 if (!string.IsNullOrEmpty(contentItem.Text))
112 {
113 Console.WriteLine($"{contentItem.Text}");
114
115 if (contentItem.TextAnnotations.Count > 0)
116 {
117 Console.WriteLine();
118 }
119
120 // Include annotations, if any.
121 foreach (TextAnnotation annotation in contentItem.TextAnnotations)
122 {
123 if (!string.IsNullOrEmpty(annotation.InputFileId))
124 {
125 Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}");
126 }
127 if (!string.IsNullOrEmpty(annotation.OutputFileId))
128 {
129 Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}");
130 }
131 }
132 }
133 if (!string.IsNullOrEmpty(contentItem.ImageFileId))
134 {
135 OpenAIFile imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId);
136 BinaryData imageBytes = await fileClient.DownloadFileAsync(contentItem.ImageFileId);
137 using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
138 imageBytes.ToStream().CopyTo(stream);
139
140 Console.WriteLine($"<image: {imageInfo.Filename}.png>");
141 }
142 }
143 Console.WriteLine();
144 }
145
146 // Optionally, delete any persistent resources you no longer need.
147 _ = await assistantClient.DeleteThreadAsync(threadRun.ThreadId);
148 _ = await assistantClient.DeleteAssistantAsync(assistant.Id);
149 _ = await fileClient.DeleteFileAsync(salesFile.Id);
150 }
151}
152
153#pragma warning restore OPENAI001