openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.0.0-beta.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/Assistants/Example01_RetrievalAugmentedGeneration.cs

155lines · 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 =
89 {
90 new ThreadInitializationMessage(new List<MessageContent>()
91 {
92 MessageContent.FromText("How well did product 113045 sell in February? Graph its trend over time."),
93 }),
94 },
95 };
96
97 ThreadRun threadRun = assistantClient.CreateThreadAndRun(assistant.Id, threadOptions);
98
99 // Check back to see when the run is done
100 do
101 {
102 Thread.Sleep(TimeSpan.FromSeconds(1));
103 threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
104 } while (!threadRun.Status.IsTerminal);
105
106 // Finally, we'll print out the full history for the thread that includes the augmented generation
107 PageableCollection<ThreadMessage> messages
108 = assistantClient.GetMessages(threadRun.ThreadId, ListOrder.OldestFirst);
109
110 foreach (ThreadMessage message in messages)
111 {
112 Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
113 foreach (MessageContent contentItem in message.Content)
114 {
115 if (!string.IsNullOrEmpty(contentItem.Text))
116 {
117 Console.WriteLine($"{contentItem.Text}");
118
119 if (contentItem.TextAnnotations.Count > 0)
120 {
121 Console.WriteLine();
122 }
123
124 // Include annotations, if any.
125 foreach (TextAnnotation annotation in contentItem.TextAnnotations)
126 {
127 if (!string.IsNullOrEmpty(annotation.InputFileId))
128 {
129 Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}");
130 }
131 if (!string.IsNullOrEmpty(annotation.OutputFileId))
132 {
133 Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}");
134 }
135 }
136 }
137 if (!string.IsNullOrEmpty(contentItem.ImageFileId))
138 {
139 OpenAIFileInfo imageInfo = fileClient.GetFile(contentItem.ImageFileId);
140 BinaryData imageBytes = fileClient.DownloadFile(contentItem.ImageFileId);
141 using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
142 imageBytes.ToStream().CopyTo(stream);
143
144 Console.WriteLine($"<image: {imageInfo.Filename}.png>");
145 }
146 }
147 Console.WriteLine();
148 }
149
150 // Optionally, delete any persistent resources you no longer need.
151 _ = assistantClient.DeleteThread(threadRun.ThreadId);
152 _ = assistantClient.DeleteAssistant(assistant);
153 _ = fileClient.DeleteFile(salesFile);
154 }
155}