1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
//! Batch API client.
use super::{map_api_error, Client};
use crate::errors::Result;
use crate::interceptor::{AfterResponseContext, BeforeRequestContext, ErrorContext};
use crate::semantic_conventions::operation_names;
use crate::time::Instant;
use crate::Error;
use openai_client_base::apis::batch_api;
use openai_client_base::models::{Batch, CreateBatchRequest, ListBatchesResponse};
/// Client for batch API.
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
pub struct BatchClient<'a, T = ()> {
pub(super) client: &'a Client<T>,
}
impl_interceptor_helpers!(BatchClient<'_, T>);
impl<T: Default + crate::MaybeSend + crate::MaybeSync> BatchClient<'_, T> {
/// Create a new batch job.
///
/// # Example
///
/// ```rust,no_run
/// use openai_ergonomic::Client;
/// use openai_ergonomic::builders::batch::{BatchJobBuilder, BatchEndpoint};
///
/// # async fn example() -> openai_ergonomic::Result<()> {
/// let client = Client::from_env()?.build();
/// let builder = BatchJobBuilder::new("file-batch-input", BatchEndpoint::ChatCompletions);
/// let batch = client.batch().create(builder).await?;
/// println!("Created batch: {}", batch.id);
/// # Ok(())
/// # }
/// ```
pub async fn create(&self, builder: crate::builders::batch::BatchJobBuilder) -> Result<Batch> {
use openai_client_base::models::create_batch_request::{CompletionWindow, Endpoint};
// Map our endpoint to the base client enum
let endpoint = match builder.endpoint() {
crate::builders::batch::BatchEndpoint::ChatCompletions => {
Endpoint::SlashV1SlashChatSlashCompletions
}
crate::builders::batch::BatchEndpoint::Embeddings => Endpoint::SlashV1SlashEmbeddings,
crate::builders::batch::BatchEndpoint::Completions => Endpoint::SlashV1SlashCompletions,
};
let mut request = CreateBatchRequest::new(
builder.input_file_id().to_string(),
endpoint,
CompletionWindow::Variant24h,
);
if builder.has_metadata() {
request.metadata = Some(Some(builder.metadata_ref().clone()));
}
// Prepare interceptor context
let mut state = T::default();
let operation = operation_names::BATCH_CREATE;
let model = "batch";
let request_json = serde_json::to_string(&request).unwrap_or_default();
// Call before_request hook
self.call_before_request(operation, model, &request_json, &mut state)
.await?;
let start_time = Instant::now();
// Make the API call
let response = match batch_api::create_batch()
.configuration(&self.client.base_configuration)
.create_batch_request(&request)
.call()
.await
{
Ok(resp) => resp,
Err(e) => {
let error = self
.handle_api_error(e, operation, model, &request_json, &state)
.await;
return Err(error);
}
};
let duration = start_time.elapsed();
// Call after_response hook
self.call_after_response(
&response,
operation,
model,
&request_json,
&state,
duration,
None,
None,
)
.await;
Ok(response)
}
/// List batch jobs.
///
/// # Example
///
/// ```rust,no_run
/// use openai_ergonomic::Client;
///
/// # async fn example() -> openai_ergonomic::Result<()> {
/// let client = Client::from_env()?.build();
/// let response = client.batch().list(None, Some(20)).await?;
/// println!("Found {} batches", response.data.len());
/// # Ok(())
/// # }
/// ```
pub async fn list(
&self,
after: Option<&str>,
limit: Option<i64>,
) -> Result<ListBatchesResponse> {
// Prepare interceptor context
let mut state = T::default();
let operation = operation_names::BATCH_LIST;
let model = "batch";
let request_json = format!("{{\"after\":{after:?},\"limit\":{limit:?}}}");
// Call before_request hook
self.call_before_request(operation, model, &request_json, &mut state)
.await?;
let start_time = Instant::now();
// Make the API call
let response = match batch_api::list_batches()
.configuration(&self.client.base_configuration)
.maybe_after(after)
.maybe_limit(limit)
.call()
.await
{
Ok(resp) => resp,
Err(e) => {
let error = self
.handle_api_error(e, operation, model, &request_json, &state)
.await;
return Err(error);
}
};
let duration = start_time.elapsed();
// Call after_response hook
self.call_after_response(
&response,
operation,
model,
&request_json,
&state,
duration,
None,
None,
)
.await;
Ok(response)
}
/// Get a specific batch job.
///
/// # Example
///
/// ```rust,no_run
/// use openai_ergonomic::Client;
///
/// # async fn example() -> openai_ergonomic::Result<()> {
/// let client = Client::from_env()?.build();
/// let batch = client.batch().get("batch_123").await?;
/// println!("Batch status: {:?}", batch.status);
/// # Ok(())
/// # }
/// ```
pub async fn get(&self, batch_id: impl Into<String>) -> Result<Batch> {
let id = batch_id.into();
// Prepare interceptor context
let mut state = T::default();
let operation = operation_names::BATCH_RETRIEVE;
let model = "batch";
let request_json = format!("{{\"batch_id\":\"{id}\"}}");
// Call before_request hook
self.call_before_request(operation, model, &request_json, &mut state)
.await?;
let start_time = Instant::now();
// Make the API call
let response = match batch_api::retrieve_batch()
.configuration(&self.client.base_configuration)
.batch_id(&id)
.call()
.await
{
Ok(resp) => resp,
Err(e) => {
let error = self
.handle_api_error(e, operation, model, &request_json, &state)
.await;
return Err(error);
}
};
let duration = start_time.elapsed();
// Call after_response hook
self.call_after_response(
&response,
operation,
model,
&request_json,
&state,
duration,
None,
None,
)
.await;
Ok(response)
}
/// Cancel a batch job.
///
/// # Example
///
/// ```rust,no_run
/// use openai_ergonomic::Client;
///
/// # async fn example() -> openai_ergonomic::Result<()> {
/// let client = Client::from_env()?.build();
/// let batch = client.batch().cancel("batch_123").await?;
/// println!("Batch cancelled: {:?}", batch.status);
/// # Ok(())
/// # }
/// ```
pub async fn cancel(&self, batch_id: impl Into<String>) -> Result<Batch> {
let id = batch_id.into();
// Prepare interceptor context
let mut state = T::default();
let operation = operation_names::BATCH_CANCEL;
let model = "batch";
let request_json = format!("{{\"batch_id\":\"{id}\"}}");
// Call before_request hook
self.call_before_request(operation, model, &request_json, &mut state)
.await?;
let start_time = Instant::now();
// Make the API call
let response = match batch_api::cancel_batch()
.configuration(&self.client.base_configuration)
.batch_id(&id)
.call()
.await
{
Ok(resp) => resp,
Err(e) => {
let error = self
.handle_api_error(e, operation, model, &request_json, &state)
.await;
return Err(error);
}
};
let duration = start_time.elapsed();
// Call after_response hook
self.call_after_response(
&response,
operation,
model,
&request_json,
&state,
duration,
None,
None,
)
.await;
Ok(response)
}
}