openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
src/Custom/FineTuning/Internal/FineTuningJobOperationToken.cs
91lines · modecode
| 1 | using System; |
| 2 | using System.ClientModel; |
| 3 | using System.Diagnostics; |
| 4 | using System.IO; |
| 5 | using System.Text.Json; |
| 6 | |
| 7 | #nullable enable |
| 8 | |
| 9 | namespace OpenAI.FineTuning; |
| 10 | |
| 11 | internal class FineTuningJobOperationToken : ContinuationToken |
| 12 | { |
| 13 | public FineTuningJobOperationToken(string jobId) |
| 14 | { |
| 15 | JobId = jobId; |
| 16 | } |
| 17 | |
| 18 | public string JobId { get; } |
| 19 | |
| 20 | public override BinaryData ToBytes() |
| 21 | { |
| 22 | using MemoryStream stream = new(); |
| 23 | using Utf8JsonWriter writer = new(stream); |
| 24 | |
| 25 | writer.WriteStartObject(); |
| 26 | |
| 27 | writer.WriteString("jobId", JobId); |
| 28 | |
| 29 | writer.WriteEndObject(); |
| 30 | |
| 31 | writer.Flush(); |
| 32 | stream.Position = 0; |
| 33 | |
| 34 | return BinaryData.FromStream(stream); |
| 35 | } |
| 36 | |
| 37 | public static FineTuningJobOperationToken FromToken(ContinuationToken continuationToken) |
| 38 | { |
| 39 | if (continuationToken is FineTuningJobOperationToken token) |
| 40 | { |
| 41 | return token; |
| 42 | } |
| 43 | |
| 44 | BinaryData data = continuationToken.ToBytes(); |
| 45 | |
| 46 | if (data.ToMemory().Length == 0) |
| 47 | { |
| 48 | throw new ArgumentException("Failed to create FineTuningJobOperationToken from provided continuationToken.", nameof(continuationToken)); |
| 49 | } |
| 50 | |
| 51 | Utf8JsonReader reader = new(data); |
| 52 | |
| 53 | string jobId = null!; |
| 54 | |
| 55 | reader.Read(); |
| 56 | |
| 57 | Debug.Assert(reader.TokenType == JsonTokenType.StartObject); |
| 58 | |
| 59 | while (reader.Read()) |
| 60 | { |
| 61 | if (reader.TokenType == JsonTokenType.EndObject) |
| 62 | { |
| 63 | break; |
| 64 | } |
| 65 | |
| 66 | Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); |
| 67 | |
| 68 | string propertyName = reader.GetString()!; |
| 69 | |
| 70 | switch (propertyName) |
| 71 | { |
| 72 | case "jobId": |
| 73 | reader.Read(); |
| 74 | Debug.Assert(reader.TokenType == JsonTokenType.String); |
| 75 | jobId = reader.GetString()!; |
| 76 | break; |
| 77 | |
| 78 | default: |
| 79 | throw new JsonException($"Unrecognized property '{propertyName}'."); |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | if (jobId is null) |
| 84 | { |
| 85 | throw new ArgumentException("Failed to create FineTuningJobOperationToken from provided continuationToken.", nameof(continuationToken)); |
| 86 | } |
| 87 | |
| 88 | return new(jobId); |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | |