openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
src/Custom/FineTuning/Internal/Pagination/AsyncFineTuningJobEventCollectionResult.cs
73lines · 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 | using System.Threading.Tasks; |
| 7 | |
| 8 | #nullable enable |
| 9 | |
| 10 | namespace OpenAI.FineTuning; |
| 11 | |
| 12 | internal class AsyncFineTuningJobEventCollectionResult : AsyncCollectionResult |
| 13 | { |
| 14 | private readonly FineTuningJobOperation _operation; |
| 15 | private readonly RequestOptions? _options; |
| 16 | |
| 17 | // Initial values |
| 18 | private readonly int? _limit; |
| 19 | private readonly string? _after; |
| 20 | |
| 21 | public AsyncFineTuningJobEventCollectionResult( |
| 22 | FineTuningJobOperation fineTuningJobOperation, |
| 23 | RequestOptions? options, |
| 24 | int? limit, string? after) |
| 25 | { |
| 26 | _operation = fineTuningJobOperation; |
| 27 | _options = options; |
| 28 | |
| 29 | _limit = limit; |
| 30 | _after = after; |
| 31 | } |
| 32 | |
| 33 | public async override IAsyncEnumerable<ClientResult> GetRawPagesAsync() |
| 34 | { |
| 35 | ClientResult page = await GetFirstPageAsync().ConfigureAwait(false); |
| 36 | yield return page; |
| 37 | |
| 38 | while (HasNextPage(page)) |
| 39 | { |
| 40 | page = await GetNextPageAsync(page); |
| 41 | yield return page; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | public override ContinuationToken? GetContinuationToken(ClientResult page) |
| 46 | { |
| 47 | Argument.AssertNotNull(page, nameof(page)); |
| 48 | |
| 49 | return FineTuningJobEventCollectionPageToken.FromResponse(page, _operation.JobId, _limit); |
| 50 | } |
| 51 | |
| 52 | public async Task<ClientResult> GetFirstPageAsync() |
| 53 | => await _operation.GetJobEventsPageAsync(_after, _limit, _options).ConfigureAwait(false); |
| 54 | |
| 55 | public async Task<ClientResult> GetNextPageAsync(ClientResult result) |
| 56 | { |
| 57 | Argument.AssertNotNull(result, nameof(result)); |
| 58 | |
| 59 | PipelineResponse response = result.GetRawResponse(); |
| 60 | |
| 61 | using JsonDocument doc = JsonDocument.Parse(response?.Content); |
| 62 | |
| 63 | JsonElement data = doc.RootElement.GetProperty("data"); |
| 64 | JsonElement lastItem = data.EnumerateArray().LastOrDefault(); |
| 65 | string? lastId = lastItem.TryGetProperty("id", out JsonElement idElement) ? |
| 66 | idElement.GetString() : null; |
| 67 | |
| 68 | return await _operation.GetJobEventsPageAsync(lastId, _limit, _options).ConfigureAwait(false); |
| 69 | } |
| 70 | |
| 71 | public static bool HasNextPage(ClientResult result) |
| 72 | => FineTuningJobEventCollectionResult.HasNextPage(result); |
| 73 | } |
| 74 | |