openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
achandmsft-patch-1

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/Custom/FineTuning/Internal/FineTuningJobOperationToken.cs

91lines · modecode

1using System;
2using System.ClientModel;
3using System.Diagnostics;
4using System.IO;
5using System.Text.Json;
6
7#nullable enable
8
9namespace OpenAI.FineTuning;
10
11internal 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