openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
examples/Chat/Example01_SimpleChat_Cancellations.cs
40lines · modecode
| 1 | using NUnit.Framework; |
| 2 | using OpenAI.Chat; |
| 3 | using System; |
| 4 | using System.ClientModel; |
| 5 | using System.ClientModel.Primitives; |
| 6 | using System.Threading; |
| 7 | |
| 8 | namespace OpenAI.Examples; |
| 9 | |
| 10 | public partial class ChatExamples |
| 11 | { |
| 12 | [Test] |
| 13 | public void Example01_SimpleChat_Cancellations() |
| 14 | { |
| 15 | ChatClient client = new(model: "gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); |
| 16 | |
| 17 | CancellationTokenSource ct = new CancellationTokenSource(); |
| 18 | RequestOptions options = new() { CancellationToken = ct.Token }; |
| 19 | |
| 20 | ChatMessage message = ChatMessage.CreateUserMessage("Say 'this is a test.'"); |
| 21 | var body = new { |
| 22 | model = "gpt-4o", |
| 23 | messages = new[] { |
| 24 | new |
| 25 | { |
| 26 | role = "user", |
| 27 | content = "Say \u0027this is a test.\u0027" |
| 28 | } |
| 29 | } |
| 30 | }; |
| 31 | |
| 32 | BinaryData json = BinaryData.FromObjectAsJson(body); |
| 33 | ClientResult result = client.CompleteChat(BinaryContent.Create(json), options); |
| 34 | |
| 35 | // The following code will be simplified in the future. |
| 36 | var wireFormat = new ModelReaderWriterOptions("W"); |
| 37 | ChatCompletion completion = ModelReaderWriter.Read<ChatCompletion>(result.GetRawResponse().Content, wireFormat); |
| 38 | Console.WriteLine($"[ASSISTANT]: {completion}"); |
| 39 | } |
| 40 | } |
| 41 | |