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 · 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
5dce104aJose Arriaga Maldonado1 years ago12// 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
8cc6643fJose Arriaga Maldonado2 years ago16public partial class AssistantExamples
9f9f2936Jose Arriaga Maldonado2 years ago17{
18[Test]
8cc6643fJose Arriaga Maldonado2 years ago19public async Task Example01_RetrievalAugmentedGenerationAsync()
9f9f2936Jose Arriaga Maldonado2 years ago20{
21OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
31c2ba63Jose Arriaga Maldonado1 years ago22OpenAIFileClient fileClient = openAIClient.GetOpenAIFileClient();
9f9f2936Jose Arriaga Maldonado2 years ago23AssistantClient assistantClient = openAIClient.GetAssistantClient();
24
25// First, let's contrive a document we'll use retrieval with and upload it.
e4af1691Jose Arriaga Maldonado1 years ago26using Stream document = BinaryData.FromBytes("""
9f9f2936Jose Arriaga Maldonado2 years ago27{
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}
e4af1691Jose Arriaga Maldonado1 years ago53"""u8.ToArray()).ToStream();
9f9f2936Jose Arriaga Maldonado2 years ago54
19ceae44ShivangiReja1 years ago55OpenAIFile salesFile = await fileClient.UploadFileAsync(
9f9f2936Jose Arriaga Maldonado2 years ago56document,
57"monthly_sales.json",
58FileUploadPurpose.Assistants);
59
60// Now, we'll create a client intended to help with that data
61AssistantCreationOptions assistantOptions = new()
62{
63Name = "Example: Contoso sales RAG",
64Instructions =
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.",
68Tools =
69{
70new FileSearchToolDefinition(),
71new CodeInterpreterToolDefinition(),
72},
73ToolResources = new()
74{
75FileSearch = new()
76{
77NewVectorStores =
78{
79new VectorStoreCreationHelper([salesFile.Id]),
80}
81}
82},
83};
84
85Assistant 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
88ThreadCreationOptions threadOptions = new()
89{
d665b61fTravis Wilson2 years ago90InitialMessages = { "How well did product 113045 sell in February? Graph its trend over time." }
9f9f2936Jose Arriaga Maldonado2 years ago91};
92
93ThreadRun threadRun = await assistantClient.CreateThreadAndRunAsync(assistant.Id, threadOptions);
94
95// Check back to see when the run is done
96do
97{
98Thread.Sleep(TimeSpan.FromSeconds(1));
99threadRun = 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
2ab1a942Jose Arriaga Maldonado1 years ago103AsyncCollectionResult<ThreadMessage> messages
104= assistantClient.GetMessagesAsync(threadRun.ThreadId, new MessageCollectionOptions() { Order = MessageCollectionOrder.Ascending });
b0f9e5c3Jose Arriaga Maldonado1 years ago105
9f9f2936Jose Arriaga Maldonado2 years ago106await foreach (ThreadMessage message in messages)
107{
108Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
109foreach (MessageContent contentItem in message.Content)
110{
111if (!string.IsNullOrEmpty(contentItem.Text))
112{
113Console.WriteLine($"{contentItem.Text}");
114
115if (contentItem.TextAnnotations.Count > 0)
116{
117Console.WriteLine();
118}
119
120// Include annotations, if any.
121foreach (TextAnnotation annotation in contentItem.TextAnnotations)
122{
123if (!string.IsNullOrEmpty(annotation.InputFileId))
124{
125Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}");
126}
127if (!string.IsNullOrEmpty(annotation.OutputFileId))
128{
129Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}");
130}
131}
132}
133if (!string.IsNullOrEmpty(contentItem.ImageFileId))
134{
19ceae44ShivangiReja1 years ago135OpenAIFile imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId);
9f9f2936Jose Arriaga Maldonado2 years ago136BinaryData imageBytes = await fileClient.DownloadFileAsync(contentItem.ImageFileId);
137using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
138imageBytes.ToStream().CopyTo(stream);
139
140Console.WriteLine($"<image: {imageInfo.Filename}.png>");
141}
142}
143Console.WriteLine();
144}
145
146// Optionally, delete any persistent resources you no longer need.
147_ = await assistantClient.DeleteThreadAsync(threadRun.ThreadId);
a330c2e7Jose Arriaga Maldonado1 years ago148_ = await assistantClient.DeleteAssistantAsync(assistant.Id);
13a9c686Jose Arriaga Maldonado1 years ago149_ = await fileClient.DeleteFileAsync(salesFile.Id);
9f9f2936Jose Arriaga Maldonado2 years ago150}
151}
5dce104aJose Arriaga Maldonado1 years ago152
153#pragma warning restore OPENAI001