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/Batch/Internal/CreateBatchOperationToken.cs

90lines · modeblame

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