openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
src/Custom/FineTuning/Internal/Pagination/FineTuningJobEventCollectionResult.cs
81lines · modecode
| 1 | using System.ClientModel; |
| 2 | using System.ClientModel.Primitives; |
| 3 | using System.Collections.Generic; |
| 4 | using System.Linq; |
| 5 | using System.Text.Json; |
| 6 | |
| 7 | #nullable enable |
| 8 | |
| 9 | namespace OpenAI.FineTuning; |
| 10 | |
| 11 | internal class FineTuningJobEventCollectionResult : CollectionResult |
| 12 | { |
| 13 | private readonly FineTuningJobOperation _operation; |
| 14 | private readonly RequestOptions? _options; |
| 15 | |
| 16 | // Initial values |
| 17 | private readonly int? _limit; |
| 18 | private readonly string? _after; |
| 19 | |
| 20 | public FineTuningJobEventCollectionResult( |
| 21 | FineTuningJobOperation fineTuningJobOperation, |
| 22 | RequestOptions? options, |
| 23 | int? limit, string? after) |
| 24 | { |
| 25 | _operation = fineTuningJobOperation; |
| 26 | _options = options; |
| 27 | |
| 28 | _limit = limit; |
| 29 | _after = after; |
| 30 | } |
| 31 | |
| 32 | public override IEnumerable<ClientResult> GetRawPages() |
| 33 | { |
| 34 | ClientResult page = GetFirstPage(); |
| 35 | yield return page; |
| 36 | |
| 37 | while (HasNextPage(page)) |
| 38 | { |
| 39 | page = GetNextPage(page); |
| 40 | yield return page; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | public override ContinuationToken? GetContinuationToken(ClientResult page) |
| 45 | { |
| 46 | Argument.AssertNotNull(page, nameof(page)); |
| 47 | |
| 48 | return FineTuningJobEventCollectionPageToken.FromResponse(page, _operation.JobId, _limit); |
| 49 | } |
| 50 | |
| 51 | public ClientResult GetFirstPage() |
| 52 | => _operation.GetJobEventsPage(_after, _limit, _options); |
| 53 | |
| 54 | public ClientResult GetNextPage(ClientResult result) |
| 55 | { |
| 56 | Argument.AssertNotNull(result, nameof(result)); |
| 57 | |
| 58 | PipelineResponse response = result.GetRawResponse(); |
| 59 | |
| 60 | using JsonDocument doc = JsonDocument.Parse(response?.Content); |
| 61 | |
| 62 | JsonElement data = doc.RootElement.GetProperty("data"); |
| 63 | JsonElement lastItem = data.EnumerateArray().LastOrDefault(); |
| 64 | string? lastId = lastItem.TryGetProperty("id", out JsonElement idElement) ? |
| 65 | idElement.GetString() : null; |
| 66 | |
| 67 | return _operation.GetJobEventsPage(lastId, _limit, _options); |
| 68 | } |
| 69 | |
| 70 | public static bool HasNextPage(ClientResult result) |
| 71 | { |
| 72 | Argument.AssertNotNull(result, nameof(result)); |
| 73 | |
| 74 | PipelineResponse response = result.GetRawResponse(); |
| 75 | |
| 76 | using JsonDocument doc = JsonDocument.Parse(response.Content); |
| 77 | bool hasMore = doc.RootElement.GetProperty("has_more"u8).GetBoolean(); |
| 78 | |
| 79 | return hasMore; |
| 80 | } |
| 81 | } |
| 82 | |