Batches
OpenAI and Anthropic run requests offline at half price and answer within 24 hours. A batch suits work nobody waits on: evals, bulk classification, summaries of a backlog.
use freyja::{BatchOutcome, BatchRequest, BatchStatus, Client, EndpointPreset, GenerateRequest, Message, Role};
use std::time::Duration;
/// A support ticket from your own system, such as a database row.
struct Ticket {
id: String,
text: String,
}
let tickets = vec![
Ticket { id: "t-1".into(), text: "I was charged twice this month".into() },
Ticket { id: "t-2".into(), text: "The export button does nothing".into() },
];
let client = Client::from_env(EndpointPreset::Anthropic)?;
let requests: Vec<BatchRequest> = tickets
.iter()
.map(|ticket| {
let request = GenerateRequest::new()
.message(Message::text(Role::System, "Classify the ticket as billing, bug or other."))
.message(Message::text(Role::User, ticket.text.clone()));
BatchRequest::new(ticket.id.clone(), request)
})
.collect();
let batch = client.submit_batch(&requests).await?;
// Keep batch.id somewhere durable: the batch outlives this process.
while client.batch(&batch.id).await?.status != BatchStatus::Ended {
tokio::time::sleep(Duration::from_secs(60)).await;
}
for result in client.batch_results(&batch.id).await? {
match result.outcome {
BatchOutcome::Succeeded(response) => println!("{}: {}", result.id, response.output_text()),
BatchOutcome::Failed(error) => eprintln!("{}: {error}", result.id),
BatchOutcome::Cancelled | BatchOutcome::Expired => eprintln!("{}: not run", result.id),
_ => {}
}
}
tickets stands for whatever your program has to process, here two support tickets with an id and a text. Each request carries an id, and its result comes back under it. Ids are 1 to 64 ASCII letters, digits, - and _, unique within the batch. Providers return results in their own order, so match on the id.
A request is the same GenerateRequest generate takes, and each result is what generate would have returned, so code that reads responses does not change. Nothing is sent when the batch is empty, an id is malformed or repeated, or a request is one Client::check refuses.
Waiting
batch(id) reports where a batch is: InProgress, Cancelling, Ended or Failed, with counts of requests answered and failed so far. Most batches end within minutes, and every one ends within a day. The id survives restarts, so a job can submit today and read results from another process tomorrow. Freyja picks no async runtime, so the waiting loop uses yours.
batch_results(id) returns InvalidRequest until the batch has ended. Failed means the provider rejected the batch as a whole and there are no results. cancel_batch(id) stops one, and requests already answered keep their results.
Per request
| Outcome | Meaning |
|---|---|
Succeeded(response) | Answered |
Failed(error) | The error generate would have returned, such as BadRequest for a request the provider rejected |
Cancelled | Not run, because the batch was cancelled |
Expired | Not run before the batch expired |
Anthropic does not bill cancelled, expired or failed requests.
Providers
| Provider | Batches |
|---|---|
| OpenAI, Responses and Chat Completions | Yes, up to 50,000 requests and a 200 MB file |
| Anthropic | Yes, up to 100,000 requests and 256 MB |
| Gemini | UnsupportedCapability: Gemini batches take the generateContent format, and Freyja speaks the Interactions API |
Usage on each response is what the provider reports. Cost tracking charges full price, so halve it for a batch.
On Anthropic, prompt caching works inside a batch and its discount adds to the batch discount. Requests that share a long system prompt are cheaper still.