openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.2.0-beta.2

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/Custom/Batch/Internal/CreateBatchOperationToken.cs

90lines · modecode

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