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 · 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 ClientPipeline _pipeline;
21 private readonly Uri _endpoint;
22
23 private readonly string _batchId;
24
25 internal CreateBatchOperation(
26 ClientPipeline pipeline,
27 Uri endpoint,
28 string batchId,
29 string status,
30 PipelineResponse response)
31 : base(response)
32 {
33 _pipeline = pipeline;
34 _endpoint = endpoint;
35 _batchId = batchId;
36
37 HasCompleted = GetHasCompleted(status);
38 RehydrationToken = new CreateBatchOperationToken(batchId);
39 }
40
41 public string BatchId => _batchId;
42
43 /// <inheritdoc/>
44 public 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>
57 public static async Task<CreateBatchOperation> RehydrateAsync(BatchClient client, ContinuationToken rehydrationToken, CancellationToken cancellationToken = default)
58 {
59 Argument.AssertNotNull(client, nameof(client));
60 Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken));
61
62 CreateBatchOperationToken token = CreateBatchOperationToken.FromToken(rehydrationToken);
63
64 ClientResult result = await client.GetBatchAsync(token.BatchId, cancellationToken.ToRequestOptions()).ConfigureAwait(false);
65 PipelineResponse response = result.GetRawResponse();
66
67 using JsonDocument doc = JsonDocument.Parse(response.Content);
68 string status = doc.RootElement.GetProperty("status"u8).GetString()!;
69
70 return 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>
84 public static CreateBatchOperation Rehydrate(BatchClient client, ContinuationToken rehydrationToken, CancellationToken cancellationToken = default)
85 {
86 Argument.AssertNotNull(client, nameof(client));
87 Argument.AssertNotNull(rehydrationToken, nameof(rehydrationToken));
88
89 CreateBatchOperationToken token = CreateBatchOperationToken.FromToken(rehydrationToken);
90
91 ClientResult result = client.GetBatch(token.BatchId, cancellationToken.ToRequestOptions());
92 PipelineResponse response = result.GetRawResponse();
93
94 using JsonDocument doc = JsonDocument.Parse(response.Content);
95 string status = doc.RootElement.GetProperty("status"u8).GetString()!;
96
97 return client.CreateCreateBatchOperation(token.BatchId, status, response);
98 }
99
100 /// <inheritdoc/>
101 public override async ValueTask<ClientResult> UpdateStatusAsync(RequestOptions? options = null)
102 {
103 ClientResult result = await GetBatchAsync(options).ConfigureAwait(false);
104
105 ApplyUpdate(result);
106
107 return result;
108 }
109
110 /// <inheritdoc/>
111 public override ClientResult UpdateStatus(RequestOptions? options = null)
112 {
113 ClientResult result = GetBatch(options);
114
115 ApplyUpdate(result);
116
117 return result;
118 }
119
120 internal async Task<CreateBatchOperation> WaitUntilAsync(bool waitUntilCompleted, RequestOptions? options)
121 {
122 if (!waitUntilCompleted) return this;
123 await WaitForCompletionAsync(options?.CancellationToken ?? default).ConfigureAwait(false);
124 return this;
125 }
126
127 internal CreateBatchOperation WaitUntil(bool waitUntilCompleted, RequestOptions? options)
128 {
129 if (!waitUntilCompleted) return this;
130 WaitForCompletion(options?.CancellationToken ?? default);
131 return this;
132 }
133
134 private void ApplyUpdate(ClientResult result)
135 {
136 PipelineResponse response = result.GetRawResponse();
137
138 using JsonDocument doc = JsonDocument.Parse(response.Content);
139 string? status = doc.RootElement.GetProperty("status"u8).GetString();
140
141 HasCompleted = GetHasCompleted(status);
142 SetRawResponse(response);
143 }
144
145 private static bool GetHasCompleted(string? status)
146 {
147 return status == InternalBatchStatus.Completed ||
148 status == InternalBatchStatus.Cancelled ||
149 status == InternalBatchStatus.Expired ||
150 status == 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>
161 public virtual async Task<ClientResult> GetBatchAsync(RequestOptions? options)
162 {
163 using PipelineMessage message = CreateRetrieveBatchRequest(_batchId, options);
164 return 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>
173 public virtual ClientResult GetBatch(RequestOptions? options)
174 {
175 using PipelineMessage message = CreateRetrieveBatchRequest(_batchId, options);
176 return 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>
185 public virtual async Task<ClientResult> CancelAsync(RequestOptions? options)
186 {
187 using PipelineMessage message = CreateCancelBatchRequest(_batchId, options);
188 return 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>
197 public virtual ClientResult Cancel(RequestOptions? options)
198 {
199 using PipelineMessage message = CreateCancelBatchRequest(_batchId, options);
200 return ClientResult.FromResponse(_pipeline.ProcessMessage(message, options));
201 }
202
203 internal virtual PipelineMessage CreateRetrieveBatchRequest(string batchId, RequestOptions? options)
204 {
205 var message = _pipeline.CreateMessage();
206 message.ResponseClassifier = PipelineMessageClassifier200;
207 var request = message.Request;
208 request.Method = "GET";
209 var uri = new ClientUriBuilder();
210 uri.Reset(_endpoint);
211 uri.AppendPath("/batches/", false);
212 uri.AppendPath(batchId, true);
213 request.Uri = uri.ToUri();
214 request.Headers.Set("Accept", "application/json");
215 message.Apply(options);
216 return message;
217 }
218
219 internal virtual PipelineMessage CreateCancelBatchRequest(string batchId, RequestOptions? options)
220 {
221 var message = _pipeline.CreateMessage();
222 message.ResponseClassifier = PipelineMessageClassifier200;
223 var request = message.Request;
224 request.Method = "POST";
225 var uri = new ClientUriBuilder();
226 uri.Reset(_endpoint);
227 uri.AppendPath("/batches/", false);
228 uri.AppendPath(batchId, true);
229 uri.AppendPath("/cancel", false);
230 request.Uri = uri.ToUri();
231 request.Headers.Set("Accept", "application/json");
232 message.Apply(options);
233 return message;
234 }
235
236 private static PipelineMessageClassifier? _pipelineMessageClassifier200;
237 private static PipelineMessageClassifier PipelineMessageClassifier200 => _pipelineMessageClassifier200 ??= PipelineMessageClassifier.Create(stackalloc ushort[] { 200 });
238}