openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.2.0-beta.4

Branches

Tags

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

Clone

HTTPS

Download ZIP

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

75lines · modecode

1using System.ClientModel;
2using System.ClientModel.Primitives;
3using System.Collections.Generic;
4using System.Text.Json;
5using System.Threading.Tasks;
6
7#nullable enable
8
9namespace OpenAI.Batch;
10
11internal class AsyncBatchCollectionResult : AsyncCollectionResult
12{
13 private readonly BatchClient _batchClient;
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 AsyncBatchCollectionResult(BatchClient batchClient,
22 ClientPipeline pipeline, RequestOptions? options,
23 int? limit, string after)
24 {
25 _batchClient = batchClient;
26 _pipeline = pipeline;
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 BatchCollectionPageToken.FromResponse(page, _limit);
50 }
51
52 public async Task<ClientResult> GetFirstPageAsync()
53 => await GetBatchesAsync(_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 string lastId = doc.RootElement.GetProperty("last_id"u8).GetString()!;
63
64 return await GetBatchesAsync(lastId, _limit, _options).ConfigureAwait(false);
65 }
66
67 public static bool HasNextPage(ClientResult result)
68 => BatchCollectionResult.HasNextPage(result);
69
70 internal virtual async Task<ClientResult> GetBatchesAsync(string? after, int? limit, RequestOptions? options)
71 {
72 using PipelineMessage message = _batchClient.CreateGetBatchesRequest(after, limit, options);
73 return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false));
74 }
75}
76