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_RetrievalAugmentedGeneration.cs

148lines · 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;
8
8cc6643fJose Arriaga Maldonado2 years ago9namespace OpenAI.Examples;
9f9f2936Jose Arriaga Maldonado2 years ago10
8cc6643fJose Arriaga Maldonado2 years ago11public partial class AssistantExamples
9f9f2936Jose Arriaga Maldonado2 years ago12{
13[Test]
8cc6643fJose Arriaga Maldonado2 years ago14public void Example01_RetrievalAugmentedGeneration()
9f9f2936Jose Arriaga Maldonado2 years ago15{
16// Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning.
a330c2e7Jose Arriaga Maldonado1 years ago17#pragma warning disable OPENAI001
9f9f2936Jose Arriaga Maldonado2 years ago18OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
31c2ba63Jose Arriaga Maldonado1 years ago19OpenAIFileClient fileClient = openAIClient.GetOpenAIFileClient();
9f9f2936Jose Arriaga Maldonado2 years ago20AssistantClient assistantClient = openAIClient.GetAssistantClient();
21
22// First, let's contrive a document we'll use retrieval with and upload it.
e4af1691Jose Arriaga Maldonado1 years ago23using Stream document = BinaryData.FromBytes("""
9f9f2936Jose Arriaga Maldonado2 years ago24{
25"description": "This document contains the sale history data for Contoso products.",
26"sales": [
27{
28"month": "January",
29"by_product": {
30"113043": 15,
31"113045": 12,
32"113049": 2
33}
34},
35{
36"month": "February",
37"by_product": {
38"113045": 22
39}
40},
41{
42"month": "March",
43"by_product": {
44"113045": 16,
45"113055": 5
46}
47}
48]
49}
e4af1691Jose Arriaga Maldonado1 years ago50"""u8.ToArray()).ToStream();
9f9f2936Jose Arriaga Maldonado2 years ago51
19ceae44ShivangiReja1 years ago52OpenAIFile salesFile = fileClient.UploadFile(
9f9f2936Jose Arriaga Maldonado2 years ago53document,
54"monthly_sales.json",
55FileUploadPurpose.Assistants);
56
57// Now, we'll create a client intended to help with that data
58AssistantCreationOptions assistantOptions = new()
59{
60Name = "Example: Contoso sales RAG",
61Instructions =
62"You are an assistant that looks up sales data and helps visualize the information based"
63+ " on user queries. When asked to generate a graph, chart, or other visualization, use"
64+ " the code interpreter tool to do so.",
65Tools =
66{
67new FileSearchToolDefinition(),
68new CodeInterpreterToolDefinition(),
69},
70ToolResources = new()
71{
72FileSearch = new()
73{
74NewVectorStores =
75{
76new VectorStoreCreationHelper([salesFile.Id]),
77}
78}
79},
80};
81
82Assistant assistant = assistantClient.CreateAssistant("gpt-4o", assistantOptions);
83
84// Now we'll create a thread with a user query about the data already associated with the assistant, then run it
85ThreadCreationOptions threadOptions = new()
86{
1c40de67Krzysztof Cwalina2 years ago87InitialMessages = { "How well did product 113045 sell in February? Graph its trend over time." }
9f9f2936Jose Arriaga Maldonado2 years ago88};
89
90ThreadRun threadRun = assistantClient.CreateThreadAndRun(assistant.Id, threadOptions);
91
92// Check back to see when the run is done
93do
94{
95Thread.Sleep(TimeSpan.FromSeconds(1));
96threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
97} while (!threadRun.Status.IsTerminal);
98
99// Finally, we'll print out the full history for the thread that includes the augmented generation
2ab1a942Jose Arriaga Maldonado1 years ago100CollectionResult<ThreadMessage> messages
101= assistantClient.GetMessages(threadRun.ThreadId, new MessageCollectionOptions() { Order = MessageCollectionOrder.Ascending });
9f9f2936Jose Arriaga Maldonado2 years ago102
103foreach (ThreadMessage message in messages)
104{
105Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
106foreach (MessageContent contentItem in message.Content)
107{
108if (!string.IsNullOrEmpty(contentItem.Text))
109{
110Console.WriteLine($"{contentItem.Text}");
111
112if (contentItem.TextAnnotations.Count > 0)
113{
114Console.WriteLine();
115}
116
117// Include annotations, if any.
118foreach (TextAnnotation annotation in contentItem.TextAnnotations)
119{
120if (!string.IsNullOrEmpty(annotation.InputFileId))
121{
122Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}");
123}
124if (!string.IsNullOrEmpty(annotation.OutputFileId))
125{
126Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}");
127}
128}
129}
130if (!string.IsNullOrEmpty(contentItem.ImageFileId))
131{
19ceae44ShivangiReja1 years ago132OpenAIFile imageInfo = fileClient.GetFile(contentItem.ImageFileId);
9f9f2936Jose Arriaga Maldonado2 years ago133BinaryData imageBytes = fileClient.DownloadFile(contentItem.ImageFileId);
134using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
135imageBytes.ToStream().CopyTo(stream);
136
137Console.WriteLine($"<image: {imageInfo.Filename}.png>");
138}
139}
140Console.WriteLine();
141}
142
143// Optionally, delete any persistent resources you no longer need.
144_ = assistantClient.DeleteThread(threadRun.ThreadId);
a330c2e7Jose Arriaga Maldonado1 years ago145_ = assistantClient.DeleteAssistant(assistant.Id);
13a9c686Jose Arriaga Maldonado1 years ago146_ = fileClient.DeleteFile(salesFile.Id);
9f9f2936Jose Arriaga Maldonado2 years ago147}
148}