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/FineTuning/Internal/Pagination/FineTuningJobCollectionResult.cs

88lines · modecode

1using System.ClientModel;
2using System.ClientModel.Primitives;
3using System.Collections.Generic;
4using System.Linq;
5using System.Text.Json;
6
7#nullable enable
8
9namespace OpenAI.FineTuning;
10
11internal class FineTuningJobCollectionResult : CollectionResult
12{
13 private readonly FineTuningClient _fineTuningClient;
14 private readonly ClientPipeline _pipeline;
15 private readonly RequestOptions? _options;
16
17 // Initial values
18 private readonly int? _limit;
19 private readonly string _after;
20
21 public FineTuningJobCollectionResult(FineTuningClient fineTuningClient,
22 ClientPipeline pipeline, RequestOptions? options,
23 int? limit, string after)
24 {
25 _fineTuningClient = fineTuningClient;
26 _pipeline = pipeline;
27 _options = options;
28
29 _limit = limit;
30 _after = after;
31 }
32
33 public override IEnumerable<ClientResult> GetRawPages()
34 {
35 ClientResult page = GetFirstPage();
36 yield return page;
37
38 while (HasNextPage(page))
39 {
40 page = GetNextPage(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 FineTuningJobCollectionPageToken.FromResponse(page, _limit);
50 }
51
52 public ClientResult GetFirstPage()
53 => GetJobs(_after, _limit, _options);
54
55 public ClientResult GetNextPage(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 GetJobs(lastId, _limit, _options);
69 }
70
71 public static bool HasNextPage(ClientResult result)
72 {
73 Argument.AssertNotNull(result, nameof(result));
74
75 PipelineResponse response = result.GetRawResponse();
76
77 using JsonDocument doc = JsonDocument.Parse(response.Content);
78 bool hasMore = doc.RootElement.GetProperty("has_more"u8).GetBoolean();
79
80 return hasMore;
81 }
82
83 internal virtual ClientResult GetJobs(string? after, int? limit, RequestOptions? options)
84 {
85 using PipelineMessage message = _fineTuningClient.CreateGetPaginatedFineTuningJobsRequest(after, limit, options);
86 return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options));
87 }
88}