openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.0.0-beta.13

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/Assistants/Example05_AssistantsWithVisionAsync.cs

73lines · modecode

1using NUnit.Framework;
2using OpenAI.Assistants;
3using OpenAI.Files;
4using System;
5using System.ClientModel;
6using System.IO;
7using System.Threading.Tasks;
8
9namespace OpenAI.Examples;
10
11public partial class AssistantExamples
12{
13 [Test]
14 public async Task Example05_AssistantsWithVisionAsync()
15 {
16 // Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning.
17 #pragma warning disable OPENAI001
18 OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
19 FileClient fileClient = openAIClient.GetFileClient();
20 AssistantClient assistantClient = openAIClient.GetAssistantClient();
21
22 OpenAIFile pictureOfAppleFile = await fileClient.UploadFileAsync(
23 Path.Combine("Assets", "picture-of-apple.png"),
24 FileUploadPurpose.Vision);
25 Uri linkToPictureOfOrange = new("https://raw.githubusercontent.com/openai/openai-dotnet/refs/heads/main/examples/Assets/picture-of-orange.png");
26
27 Assistant assistant = await assistantClient.CreateAssistantAsync(
28 "gpt-4o",
29 new AssistantCreationOptions()
30 {
31 Instructions = "When asked a question, attempt to answer very concisely. "
32 + "Prefer one-sentence answers whenever feasible."
33 });
34
35 AssistantThread thread = await assistantClient.CreateThreadAsync(new ThreadCreationOptions()
36 {
37 InitialMessages =
38 {
39 new ThreadInitializationMessage(
40 MessageRole.User,
41 [
42 "Hello, assistant! Please compare these two images for me:",
43 MessageContent.FromImageFileId(pictureOfAppleFile.Id),
44 MessageContent.FromImageUri(linkToPictureOfOrange),
45 ]),
46 }
47 });
48
49 AsyncCollectionResult<StreamingUpdate> streamingUpdates = assistantClient.CreateRunStreamingAsync(
50 thread.Id,
51 assistant.Id,
52 new RunCreationOptions()
53 {
54 AdditionalInstructions = "When possible, try to sneak in puns if you're asked to compare things.",
55 });
56
57 await foreach (StreamingUpdate streamingUpdate in streamingUpdates)
58 {
59 if (streamingUpdate.UpdateKind == StreamingUpdateReason.RunCreated)
60 {
61 Console.WriteLine($"--- Run started! ---");
62 }
63 if (streamingUpdate is MessageContentUpdate contentUpdate)
64 {
65 Console.Write(contentUpdate.Text);
66 }
67 }
68
69 _ = await fileClient.DeleteFileAsync(pictureOfAppleFile.Id);
70 _ = await assistantClient.DeleteThreadAsync(thread.Id);
71 _ = await assistantClient.DeleteAssistantAsync(assistant.Id);
72 }
73}