openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.2.0-beta.2

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/Custom/Batch/CreateBatchOperation.Protocol.cs

238lines · modeblame

a330c2e7Jose Arriaga Maldonado1 years ago1using System;
2using System.ClientModel;
3using System.ClientModel.Primitives;
4using System.Diagnostics.CodeAnalysis;
5using System.Text.Json;
6using System.Threading;
7using System.Threading.Tasks;
8
9#nullable enable
10
11namespace OpenAI.Batch;
12
13/// <summary>
14/// A long-running operation for executing a batch from an uploaded file of
15/// requests.
16/// </summary>
17[Experimental("OPENAI001")]
18public class CreateBatchOperation : OperationResult
19{
20private readonly ClientPipeline _pipeline;
21private readonly Uri _endpoint;
22
23private readonly string _batchId;
24
25internal CreateBatchOperation(
26ClientPipeline pipeline,
27Uri endpoint,
28string batchId,
29string status,
30PipelineResponse response)
31: base(response)
32{
33_pipeline = pipeline;
34_endpoint = endpoint;
35_batchId = batchId;
36
37HasCompleted = GetHasCompleted(status);
38RehydrationToken = new CreateBatchOperationToken(batchId);
39}
40
41public string BatchId => _batchId;
42
43/// <inheritdoc/>
44public override ContinuationToken? RehydrationToken { get; protected set; }
45
46/// <summary>
47/// Recreates a <see cref="CreateBatchOperation"/> from a rehydration token.
48/// </summary>
49/// <param name="client"> The <see cref="BatchClient"/> used to obtain the
50/// operation status from the service. </param>
51/// <param name="rehydrationToken"> The rehydration token corresponding to
52/// the operation to rehydrate. </param>
53/// <param name="cancellationToken"> A token that can be used to cancel the
54/// request. </param>
55/// <returns> The rehydrated operation. </returns>
56/// <exception cref="ArgumentNullException"> <paramref name="client"/> or <paramref name="rehydrationToken"/> is null. </exception>
57public static async Task<CreateBatchOperation> RehydrateAsync(BatchClient client, ContinuationToken rehydrationToken, CancellationToken cancellationToken = default)
58{
59Argument.AssertNotNull(client, nameof(client));
60Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken));
61
62CreateBatchOperationToken token = CreateBatchOperationToken.FromToken(rehydrationToken);
63
64ClientResult result = await client.GetBatchAsync(token.BatchId, cancellationToken.ToRequestOptions()).ConfigureAwait(false);
65PipelineResponse response = result.GetRawResponse();
66
67using JsonDocument doc = JsonDocument.Parse(response.Content);
68string status = doc.RootElement.GetProperty("status"u8).GetString()!;
69
70return client.CreateCreateBatchOperation(token.BatchId, status, response);
71}
72
73/// <summary>
74/// Recreates a <see cref="CreateBatchOperation"/> from a rehydration token.
75/// </summary>
76/// <param name="client"> The <see cref="BatchClient"/> used to obtain the
77/// operation status from the service. </param>
78/// <param name="rehydrationToken"> The rehydration token corresponding to
79/// the operation to rehydrate. </param>
80/// <param name="cancellationToken"> A token that can be used to cancel the
81/// request. </param>
82/// <returns> The rehydrated operation. </returns>
83/// <exception cref="ArgumentNullException"> <paramref name="client"/> or <paramref name="rehydrationToken"/> is null. </exception>
84public static CreateBatchOperation Rehydrate(BatchClient client, ContinuationToken rehydrationToken, CancellationToken cancellationToken = default)
85{
86Argument.AssertNotNull(client, nameof(client));
87Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken));
88
89CreateBatchOperationToken token = CreateBatchOperationToken.FromToken(rehydrationToken);
90
91ClientResult result = client.GetBatch(token.BatchId, cancellationToken.ToRequestOptions());
92PipelineResponse response = result.GetRawResponse();
93
94using JsonDocument doc = JsonDocument.Parse(response.Content);
95string status = doc.RootElement.GetProperty("status"u8).GetString()!;
96
97return client.CreateCreateBatchOperation(token.BatchId, status, response);
98}
99
100/// <inheritdoc/>
101public override async ValueTask<ClientResult> UpdateStatusAsync(RequestOptions? options = null)
102{
103ClientResult result = await GetBatchAsync(options).ConfigureAwait(false);
104
105ApplyUpdate(result);
106
107return result;
108}
109
110/// <inheritdoc/>
111public override ClientResult UpdateStatus(RequestOptions? options = null)
112{
113ClientResult result = GetBatch(options);
114
115ApplyUpdate(result);
116
117return result;
118}
119
120internal async Task<CreateBatchOperation> WaitUntilAsync(bool waitUntilCompleted, RequestOptions? options)
121{
122if (!waitUntilCompleted) return this;
123await WaitForCompletionAsync(options?.CancellationToken ?? default).ConfigureAwait(false);
124return this;
125}
126
127internal CreateBatchOperation WaitUntil(bool waitUntilCompleted, RequestOptions? options)
128{
129if (!waitUntilCompleted) return this;
130WaitForCompletion(options?.CancellationToken ?? default);
131return this;
132}
133
134private void ApplyUpdate(ClientResult result)
135{
136PipelineResponse response = result.GetRawResponse();
137
138using JsonDocument doc = JsonDocument.Parse(response.Content);
139string? status = doc.RootElement.GetProperty("status"u8).GetString();
140
141HasCompleted = GetHasCompleted(status);
142SetRawResponse(response);
143}
144
145private static bool GetHasCompleted(string? status)
146{
147return status == InternalBatchStatus.Completed ||
148status == InternalBatchStatus.Cancelled ||
149status == InternalBatchStatus.Expired ||
150status == InternalBatchStatus.Failed;
151}
152
153// Generated protocol methods
154
155/// <summary>
156/// [Protocol Method] Retrieves a batch.
157/// </summary>
158/// <param name="options"> The request options, which can override default behaviors of the client pipeline on a per-call basis. </param>
159/// <exception cref="ClientResultException"> Service returned a non-success status code. </exception>
160/// <returns> The response returned from the service. </returns>
161public virtual async Task<ClientResult> GetBatchAsync(RequestOptions? options)
162{
163using PipelineMessage message = CreateRetrieveBatchRequest(_batchId, options);
164return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false));
165}
166
167/// <summary>
168/// [Protocol Method] Retrieves a batch.
169/// </summary>
170/// <param name="options"> The request options, which can override default behaviors of the client pipeline on a per-call basis. </param>
171/// <exception cref="ClientResultException"> Service returned a non-success status code. </exception>
172/// <returns> The response returned from the service. </returns>
173public virtual ClientResult GetBatch(RequestOptions? options)
174{
175using PipelineMessage message = CreateRetrieveBatchRequest(_batchId, options);
176return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options));
177}
178
179/// <summary>
180/// [Protocol Method] Cancels an in-progress batch.
181/// </summary>
182/// <param name="options"> The request options, which can override default behaviors of the client pipeline on a per-call basis. </param>
183/// <exception cref="ClientResultException"> Service returned a non-success status code. </exception>
184/// <returns> The response returned from the service. </returns>
185public virtual async Task<ClientResult> CancelAsync(RequestOptions? options)
186{
187using PipelineMessage message = CreateCancelBatchRequest(_batchId, options);
188return ClientResult.FromResponse(await _pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false));
189}
190
191/// <summary>
192/// [Protocol Method] Cancels an in-progress batch.
193/// </summary>
194/// <param name="options"> The request options, which can override default behaviors of the client pipeline on a per-call basis. </param>
195/// <exception cref="ClientResultException"> Service returned a non-success status code. </exception>
196/// <returns> The response returned from the service. </returns>
197public virtual ClientResult Cancel(RequestOptions? options)
198{
199using PipelineMessage message = CreateCancelBatchRequest(_batchId, options);
200return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options));
201}
202
203internal virtual PipelineMessage CreateRetrieveBatchRequest(string batchId, RequestOptions? options)
204{
205var message = _pipeline.CreateMessage();
206message.ResponseClassifier = PipelineMessageClassifier200;
207var request = message.Request;
208request.Method = "GET";
209var uri = new ClientUriBuilder();
210uri.Reset(_endpoint);
211uri.AppendPath("/batches/", false);
212uri.AppendPath(batchId, true);
213request.Uri = uri.ToUri();
214request.Headers.Set("Accept", "application/json");
215message.Apply(options);
216return message;
217}
218
219internal virtual PipelineMessage CreateCancelBatchRequest(string batchId, RequestOptions? options)
220{
221var message = _pipeline.CreateMessage();
222message.ResponseClassifier = PipelineMessageClassifier200;
223var request = message.Request;
224request.Method = "POST";
225var uri = new ClientUriBuilder();
226uri.Reset(_endpoint);
227uri.AppendPath("/batches/", false);
228uri.AppendPath(batchId, true);
229uri.AppendPath("/cancel", false);
230request.Uri = uri.ToUri();
231request.Headers.Set("Accept", "application/json");
232message.Apply(options);
233return message;
234}
235
236private static PipelineMessageClassifier? _pipelineMessageClassifier200;
237private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 });
238}