openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.0.0-beta.8

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/Assistants/Example01_RetrievalAugmentedGeneration.cs

150lines · modecode

1using NUnit.Framework;
2using OpenAI.Assistants;
3using OpenAI.Files;
4using System;
5using System.ClientModel;
6using System.Collections.Generic;
7using System.IO;
8using System.Threading;
9
10namespace OpenAI.Examples;
11
12public partial class AssistantExamples
13{
14 [Test]
15 public void Example01_RetrievalAugmentedGeneration()
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 FileClient fileClient = openAIClient.GetFileClient();
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.FromString("""
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 """).ToStream();
52
53 OpenAIFileInfo salesFile = fileClient.UploadFile(
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 = assistantClient.CreateAssistant("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 = assistantClient.CreateThreadAndRun(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 PageCollection<ThreadMessage> messagePages
102 = assistantClient.GetMessages(threadRun.ThreadId, new MessageCollectionOptions() { Order = ListOrder.OldestFirst });
103 IEnumerable<ThreadMessage> messages = messagePages.GetAllValues();
104
105 foreach (ThreadMessage message in messages)
106 {
107 Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
108 foreach (MessageContent contentItem in message.Content)
109 {
110 if (!string.IsNullOrEmpty(contentItem.Text))
111 {
112 Console.WriteLine($"{contentItem.Text}");
113
114 if (contentItem.TextAnnotations.Count > 0)
115 {
116 Console.WriteLine();
117 }
118
119 // Include annotations, if any.
120 foreach (TextAnnotation annotation in contentItem.TextAnnotations)
121 {
122 if (!string.IsNullOrEmpty(annotation.InputFileId))
123 {
124 Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}");
125 }
126 if (!string.IsNullOrEmpty(annotation.OutputFileId))
127 {
128 Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}");
129 }
130 }
131 }
132 if (!string.IsNullOrEmpty(contentItem.ImageFileId))
133 {
134 OpenAIFileInfo imageInfo = fileClient.GetFile(contentItem.ImageFileId);
135 BinaryData imageBytes = fileClient.DownloadFile(contentItem.ImageFileId);
136 using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
137 imageBytes.ToStream().CopyTo(stream);
138
139 Console.WriteLine($"<image: {imageInfo.Filename}.png>");
140 }
141 }
142 Console.WriteLine();
143 }
144
145 // Optionally, delete any persistent resources you no longer need.
146 _ = assistantClient.DeleteThread(threadRun.ThreadId);
147 _ = assistantClient.DeleteAssistant(assistant);
148 _ = fileClient.DeleteFile(salesFile);
149 }
150}
151