openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.1.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/Custom/Batch/Internal/Pagination/BatchCollectionPageToken.cs

94lines · modecode

1using System;
2using System.ClientModel;
3using System.ClientModel.Primitives;
4using System.Diagnostics;
5using System.Text.Json;
6
7#nullable enable
8
9namespace OpenAI.Batch;
10
11internal class BatchCollectionPageToken : ContinuationToken
12{
13 protected BatchCollectionPageToken(int? limit, string? after)
14 {
15 Limit = limit;
16 After = after;
17 }
18
19 public int? Limit { get; }
20
21 public string? After { get; }
22
23 public static BatchCollectionPageToken FromToken(ContinuationToken pageToken)
24 {
25 if (pageToken is BatchCollectionPageToken token)
26 {
27 return token;
28 }
29
30 BinaryData data = pageToken.ToBytes();
31
32 if (data.ToMemory().Length == 0)
33 {
34 throw new ArgumentException("Failed to create BatchCollectionPageToken from provided pageToken.", nameof(pageToken));
35 }
36
37 Utf8JsonReader reader = new(data);
38
39 int? limit = null;
40 string? after = null;
41
42 reader.Read();
43
44 Debug.Assert(reader.TokenType == JsonTokenType.StartObject);
45
46 while (reader.Read())
47 {
48 if (reader.TokenType == JsonTokenType.EndObject)
49 {
50 break;
51 }
52
53 Debug.Assert(reader.TokenType == JsonTokenType.PropertyName);
54
55 string propertyName = reader.GetString()!;
56
57 switch (propertyName)
58 {
59 case "limit":
60 reader.Read();
61 Debug.Assert(reader.TokenType == JsonTokenType.Number);
62 limit = reader.GetInt32();
63 break;
64 case "after":
65 reader.Read();
66 Debug.Assert(reader.TokenType == JsonTokenType.String);
67 after = reader.GetString();
68 break;
69 default:
70 throw new JsonException($"Unrecognized property '{propertyName}'.");
71 }
72 }
73
74 return new(limit, after);
75 }
76
77 public static BatchCollectionPageToken FromOptions(int? limit, string? after)
78 => new(limit, after);
79
80 public static BatchCollectionPageToken? FromResponse(ClientResult result, int? limit)
81 {
82 PipelineResponse response = result.GetRawResponse();
83 using JsonDocument doc = JsonDocument.Parse(response.Content);
84 string lastId = doc.RootElement.GetProperty("last_id"u8).GetString()!;
85 bool hasMore = doc.RootElement.GetProperty("has_more"u8).GetBoolean();
86
87 if (!hasMore || lastId is null)
88 {
89 return null;
90 }
91
92 return new(limit, lastId);
93 }
94}
95