openai/openai-dotnet

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
fe4d6cf1ccfea48fa5c2baf67103495ac9b459dd

Branches

Tags

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

Clone

HTTPS

Download ZIP

OpenAI/src/Custom/Batch/CreateBatchOperation.Protocol.cs

235lines · modecode

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