openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/fix-security-dependencies

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/Assistants/Example05_AssistantsWithVisionAsync.cs

78lines · 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
11// This example uses experimental APIs which are subject to change. To use experimental APIs,
12// please acknowledge their experimental status by suppressing the corresponding warning.
13#pragma warning disable OPENAI001
14
15public partial class AssistantExamples
16{
17 [Test]
18 public async Task Example05_AssistantsWithVisionAsync()
19 {
20 OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
21 OpenAIFileClient fileClient = openAIClient.GetOpenAIFileClient();
22 AssistantClient assistantClient = openAIClient.GetAssistantClient();
23
24 OpenAIFile pictureOfAppleFile = await fileClient.UploadFileAsync(
25 Path.Combine("Assets", "images_apple.png"),
26 FileUploadPurpose.Vision);
27
28 Uri linkToPictureOfOrange = new("https://raw.githubusercontent.com/openai/openai-dotnet/refs/heads/main/examples/Assets/images_orange.png");
29
30 Assistant assistant = await assistantClient.CreateAssistantAsync(
31 "gpt-4o",
32 new AssistantCreationOptions()
33 {
34 Instructions = "When asked a question, attempt to answer very concisely. "
35 + "Prefer one-sentence answers whenever feasible."
36 });
37
38 AssistantThread thread = await assistantClient.CreateThreadAsync(new ThreadCreationOptions()
39 {
40 InitialMessages =
41 {
42 new ThreadInitializationMessage(
43 MessageRole.User,
44 [
45 "Hello, assistant! Please compare these two images for me:",
46 MessageContent.FromImageFileId(pictureOfAppleFile.Id),
47 MessageContent.FromImageUri(linkToPictureOfOrange),
48 ]),
49 }
50 });
51
52 AsyncCollectionResult<StreamingUpdate> streamingUpdates = assistantClient.CreateRunStreamingAsync(
53 thread.Id,
54 assistant.Id,
55 new RunCreationOptions()
56 {
57 AdditionalInstructions = "When possible, try to sneak in puns if you're asked to compare things.",
58 });
59
60 await foreach (StreamingUpdate streamingUpdate in streamingUpdates)
61 {
62 if (streamingUpdate.UpdateKind == StreamingUpdateReason.RunCreated)
63 {
64 Console.WriteLine($"--- Run started! ---");
65 }
66 if (streamingUpdate is MessageContentUpdate contentUpdate)
67 {
68 Console.Write(contentUpdate.Text);
69 }
70 }
71
72 _ = await fileClient.DeleteFileAsync(pictureOfAppleFile.Id);
73 _ = await assistantClient.DeleteThreadAsync(thread.Id);
74 _ = await assistantClient.DeleteAssistantAsync(assistant.Id);
75 }
76}
77
78#pragma warning restore OPENAI001