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

151lines · modeblame

9f9f2936Jose Arriaga Maldonado2 years ago1using NUnit.Framework;
2using OpenAI.Assistants;
3using OpenAI.Files;
4using System;
5using System.ClientModel;
6using System.Collections.Generic;
7using System.IO;
8using System.Threading;
9using System.Threading.Tasks;
10
8cc6643fJose Arriaga Maldonado2 years ago11namespace OpenAI.Examples;
9f9f2936Jose Arriaga Maldonado2 years ago12
8cc6643fJose Arriaga Maldonado2 years ago13public partial class AssistantExamples
9f9f2936Jose Arriaga Maldonado2 years ago14{
15[Test]
8cc6643fJose Arriaga Maldonado2 years ago16public async Task Example01_RetrievalAugmentedGenerationAsync()
9f9f2936Jose Arriaga Maldonado2 years ago17{
18// Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning.
19#pragma warning disable OPENAI001
20OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
21FileClient fileClient = openAIClient.GetFileClient();
22AssistantClient assistantClient = openAIClient.GetAssistantClient();
23
24// First, let's contrive a document we'll use retrieval with and upload it.
25using Stream document = BinaryData.FromString("""
26{
27"description": "This document contains the sale history data for Contoso products.",
28"sales": [
29{
30"month": "January",
31"by_product": {
32"113043": 15,
33"113045": 12,
34"113049": 2
35}
36},
37{
38"month": "February",
39"by_product": {
40"113045": 22
41}
42},
43{
44"month": "March",
45"by_product": {
46"113045": 16,
47"113055": 5
48}
49}
50]
51}
52""").ToStream();
53
54OpenAIFileInfo salesFile = await fileClient.UploadFileAsync(
55document,
56"monthly_sales.json",
57FileUploadPurpose.Assistants);
58
59// Now, we'll create a client intended to help with that data
60AssistantCreationOptions assistantOptions = new()
61{
62Name = "Example: Contoso sales RAG",
63Instructions =
64"You are an assistant that looks up sales data and helps visualize the information based"
65+ " on user queries. When asked to generate a graph, chart, or other visualization, use"
66+ " the code interpreter tool to do so.",
67Tools =
68{
69new FileSearchToolDefinition(),
70new CodeInterpreterToolDefinition(),
71},
72ToolResources = new()
73{
74FileSearch = new()
75{
76NewVectorStores =
77{
78new VectorStoreCreationHelper([salesFile.Id]),
79}
80}
81},
82};
83
84Assistant assistant = await assistantClient.CreateAssistantAsync("gpt-4o", assistantOptions);
85
86// Now we'll create a thread with a user query about the data already associated with the assistant, then run it
87ThreadCreationOptions threadOptions = new()
88{
d665b61fTravis Wilson2 years ago89InitialMessages = { "How well did product 113045 sell in February? Graph its trend over time." }
9f9f2936Jose Arriaga Maldonado2 years ago90};
91
92ThreadRun threadRun = await assistantClient.CreateThreadAndRunAsync(assistant.Id, threadOptions);
93
94// Check back to see when the run is done
95do
96{
97Thread.Sleep(TimeSpan.FromSeconds(1));
98threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
99} while (!threadRun.Status.IsTerminal);
100
101// Finally, we'll print out the full history for the thread that includes the augmented generation
7bdecfd8Anne Thompson2 years ago102AsyncPageCollection<ThreadMessage> messagePages
103= assistantClient.GetMessagesAsync(threadRun.ThreadId, new MessageCollectionOptions() { Order = ListOrder.OldestFirst });
104IAsyncEnumerable<ThreadMessage> messages = messagePages.GetAllValuesAsync();
9f9f2936Jose Arriaga Maldonado2 years ago105
106await 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{
135OpenAIFileInfo imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId);
136BinaryData 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);
148_ = await assistantClient.DeleteAssistantAsync(assistant);
149_ = await fileClient.DeleteFileAsync(salesFile);
150}
151}