openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.0.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/Custom/FineTuning/Internal/Pagination/AsyncFineTuningJobCollectionResult.cs

81lines · modecode

1using System.ClientModel;
2using System.ClientModel.Primitives;
3using System.Collections.Generic;
4using System.Linq;
5using System.Text.Json;
6using System.Threading.Tasks;
7
8#nullable enable
9
10namespace OpenAI.FineTuning;
11
12internal class AsyncFineTuningJobCollectionResult : AsyncCollectionResult
13{
14 private readonly FineTuningClient _fineTuningClient;
15 private readonly ClientPipeline _pipeline;
16 private readonly RequestOptions? _options;
17
18 // Initial values
19 private readonly int? _limit;
20 private readonly string _after;
21
22 public AsyncFineTuningJobCollectionResult(FineTuningClient fineTuningClient,
23 ClientPipeline pipeline, RequestOptions? options,
24 int? limit, string after)
25 {
26 _fineTuningClient = fineTuningClient;
27 _pipeline = pipeline;
28 _options = options;
29
30 _limit = limit;
31 _after = after;
32 }
33
34
35 public async override IAsyncEnumerable<ClientResult> GetRawPagesAsync()
36 {
37 ClientResult page = await GetFirstPageAsync().ConfigureAwait(false);
38 yield return page;
39
40 while (HasNextPage(page))
41 {
42 page = await GetNextPageAsync(page);
43 yield return page;
44 }
45 }
46
47 public override ContinuationToken? GetContinuationToken(ClientResult page)
48 {
49 Argument.AssertNotNull(page, nameof(page));
50
51 return FineTuningJobCollectionPageToken.FromResponse(page, _limit);
52 }
53
54 public async Task<ClientResult> GetFirstPageAsync()
55 => await GetJobsAsync(_after, _limit, _options).ConfigureAwait(false);
56
57 public async Task<ClientResult> GetNextPageAsync(ClientResult result)
58 {
59 Argument.AssertNotNull(result, nameof(result));
60
61 PipelineResponse response = result.GetRawResponse();
62
63 using JsonDocument doc = JsonDocument.Parse(response?.Content);
64
65 JsonElement data = doc.RootElement.GetProperty("data");
66 JsonElement lastItem = data.EnumerateArray().LastOrDefault();
67 string? lastId = lastItem.TryGetProperty("id", out JsonElement idElement) ?
68 idElement.GetString() : null;
69
70 return await GetJobsAsync(lastId, _limit, _options).ConfigureAwait(false);
71 }
72
73 public static bool HasNextPage(ClientResult result)
74 => FineTuningJobCollectionResult.HasNextPage(result);
75
76 internal virtual async Task<ClientResult> GetJobsAsync(string? after, int? limit, RequestOptions? options)
77 {
78 using PipelineMessage message = _fineTuningClient.CreateGetPaginatedFineTuningJobsRequest(after, limit, options);
79 return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false));
80 }
81}
82