async_openai_wasm/
batches.rs

1use serde::Serialize;
2
3use crate::{
4    Client,
5    config::Config,
6    error::OpenAIError,
7    types::{Batch, BatchRequest, ListBatchesResponse},
8};
9
10/// Create large batches of API requests for asynchronous processing. The Batch API returns completions within 24 hours for a 50% discount.
11///
12/// Related guide: [Batch](https://platform.openai.com/docs/guides/batch)
13pub struct Batches<'c, C: Config> {
14    client: &'c Client<C>,
15}
16
17impl<'c, C: Config> Batches<'c, C> {
18    pub fn new(client: &'c Client<C>) -> Self {
19        Self { client }
20    }
21
22    /// Creates and executes a batch from an uploaded file of requests
23    #[crate::byot(T0 = serde::Serialize, R = serde::de::DeserializeOwned)]
24    pub async fn create(&self, request: BatchRequest) -> Result<Batch, OpenAIError> {
25        self.client.post("/batches", request).await
26    }
27
28    /// List your organization's batches.
29    #[crate::byot(T0 = serde::Serialize, R = serde::de::DeserializeOwned)]
30    pub async fn list<Q>(&self, query: &Q) -> Result<ListBatchesResponse, OpenAIError>
31    where
32        Q: Serialize + ?Sized,
33    {
34        self.client.get_with_query("/batches", &query).await
35    }
36
37    /// Retrieves a batch.
38    #[crate::byot(T0 = std::fmt::Display, R = serde::de::DeserializeOwned)]
39    pub async fn retrieve(&self, batch_id: &str) -> Result<Batch, OpenAIError> {
40        self.client.get(&format!("/batches/{batch_id}")).await
41    }
42
43    /// Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, before changing to `cancelled`, where it will have partial results (if any) available in the output file.
44    #[crate::byot(T0 = std::fmt::Display, R = serde::de::DeserializeOwned)]
45    pub async fn cancel(&self, batch_id: &str) -> Result<Batch, OpenAIError> {
46        self.client
47            .post(
48                &format!("/batches/{batch_id}/cancel"),
49                serde_json::json!({}),
50            )
51            .await
52    }
53}