Prompt Chain

Process Data in Batches with OpenAI API

Walks through OpenAI's Batch API for lower-cost async jobs, with movie-categorization and image-captioning examples.

Works with openai

76
Spark score
out of 100
Updated 3 days ago
Version 1.0.0
Models

Add to Favorites

Why it matters

Leverage the OpenAI Batch API to process large volumes of data asynchronously at a lower cost and with higher rate limits. This enables efficient content enrichment, categorization, and analysis for various applications.

Outcomes

What it gets done

01

Process movie categorization and summarization for large datasets.

02

Generate image captions for collections of visual content.

03

Prepare and submit batch jobs to the OpenAI API.

04

Retrieve and match results from asynchronous batch processing.

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/oai-batchprocessing | bash

Steps

Steps in the chain

01
Setup
02
Loading data for movie categorization
03
Processing step - Test with Chat Completions
04
Creating the batch file
05
Uploading the file
06
Creating the batch job
07
Checking batch status
08
Retrieving results
09
Reading results
10
Loading data for image captioning
11
Processing step - Image captioning
12
Creating batch job for image captioning
13
Getting results for image captioning

Overview

Batch processing with the Batch API

An OpenAI cookbook demonstrating the Batch API for lower-cost async jobs, with examples categorizing movies via JSON mode and captioning images via vision. Use the Batch API for large, latency-tolerant workloads like content tagging or bulk summarization. Not suited for anything needing an immediate reply.

What it does

Demonstrates OpenAI's Batch API for running async batch jobs at lower cost and higher rate limits than the standard Chat Completions endpoint, via a five-step lifecycle: uploading a batch file, creating the batch job, checking its status, retrieving results, and reading them. Walks through two practical examples: categorizing IMDB's top 1000 movies with gpt-4o-mini, using OpenAI's JSON mode (documented separately in OpenAI's text-generation guide) to extract a structured result shaped like {categories: ['category1', 'category2', 'category3'], summary: '1-sentence summary'} for each movie; and captioning Amazon furniture images with gpt-4-turbo's vision capabilities, following the same prototype-then-batch workflow.

When to use - and when NOT to

Use the Batch API for large, async-tolerant workloads - tagging, captioning, or enriching marketplace or blog content, categorizing and suggesting answers for support tickets, sentiment analysis on customer feedback at scale, or generating summaries and translations across document collections - where you don't need a synchronous response. It is not suited for anything requiring an immediate reply - completion time depends on global usage, and status must be polled rather than awaited inline.

Inputs and outputs

Each example first prototypes its prompt against the regular Chat Completions endpoint, then builds a batch file: a .jsonl file with one JSON request per line, each carrying a unique custom_id, method: "POST", url: "/v1/chat/completions", and a body with model, messages, and other Chat Completions parameters.

{
    "custom_id": <REQUEST_ID>,
    "method": "POST",
    "url": "/v1/chat/completions",
    "body": {
        "model": <MODEL>,
        "messages": <MESSAGES>,
        // other parameters
    }
}

The file is uploaded, a batch job is created from it, and status is polled until it reads completed - this can take up to 24 hours, though it's usually completed faster. Results come back out of order, so the custom_id on each result is what matches it back to its original request.

Integrations

Works with most current OpenAI chat models through the same parameter set as the Chat Completions endpoint - the cookbook names gpt-4o, gpt-4o-mini, gpt-4-turbo, and gpt-3.5-turbo as supported.

Who it's for

Teams with large-volume, latency-tolerant LLM workloads - content tagging, support-ticket categorization, sentiment analysis, bulk summarization or translation - who want to cut costs by moving async-compatible jobs off the synchronous Chat Completions endpoint onto the Batch API. The cookbook's own closing recommendation: since the Batch API reduces costs significantly, switch every workload that can tolerate async processing over to a batch job.

Source README

Batch processing with the Batch API

The new Batch API allows to create async batch jobs for a lower price and with higher rate limits.

Batches will be completed within 24h, but may be processed sooner depending on global usage.

Ideal use cases for the Batch API include:

  • Tagging, captioning, or enriching content on a marketplace or blog
  • Categorizing and suggesting answers for support tickets
  • Performing sentiment analysis on large datasets of customer feedback
  • Generating summaries or translations for collections of documents or articles

and much more!

This cookbook will walk you through how to use the Batch API with a couple of practical examples.

We will start with an example to categorize movies using gpt-4o-mini, and then cover how we can use the vision capabilities of this model to caption images.

Please note that multiple models are available through the Batch API, and that you can use the same parameters in your Batch API calls as with the Chat Completions endpoint.

Setup

First example: Categorizing movies

In this example, we will use gpt-4o-mini to extract movie categories from a description of the movie. We will also extract a 1-sentence summary from this description.

We will use JSON mode to extract categories as an array of strings and the 1-sentence summary in a structured format.

For each movie, we want to get a result that looks like this:

{
    categories: ['category1', 'category2', 'category3'],
    summary: '1-sentence summary'
}

Loading data

We will use the IMDB top 1000 movies dataset for this example.

Processing step

Here, we will prepare our requests by first trying them out with the Chat Completions endpoint.

Once we're happy with the results, we can move on to creating the batch file.

Creating the batch file

The batch file, in the jsonl format, should contain one line (json object) per request.
Each request is defined as such:

{
    "custom_id": <REQUEST_ID>,
    "method": "POST",
    "url": "/v1/chat/completions",
    "body": {
        "model": <MODEL>,
        "messages": <MESSAGES>,
        // other parameters
    }
}

Note: the request ID should be unique per batch. This is what you can use to match results to the initial input files, as requests will not be returned in the same order.

Uploading the file

Creating the batch job

Checking batch status

Note: this can take up to 24h, but it will usually be completed faster.

You can continue checking until the status is 'completed'.

Retrieving results

Reading results

Reminder: the results are not in the same order as in the input file.
Make sure to check the custom_id to match the results against the input requests

Second example: Captioning images

In this example, we will use gpt-4-turbo to caption images of furniture items.

We will use the vision capabilities of the model to analyze the images and generate the captions.

Loading data

We will use the Amazon furniture dataset for this example.

Processing step

Again, we will first prepare our requests with the Chat Completions endpoint, and create the batch file afterwards.

Creating the batch job

As with the first example, we will create an array of json tasks to generate a jsonl file and use it to create the batch job.

Getting results

As with the first example, we can retrieve results once the batch job is done.

Reminder: the results are not in the same order as in the input file.
Make sure to check the custom_id to match the results against the input requests

Wrapping up

In this cookbook, we have seen two examples of how to use the new Batch API, but keep in mind that the Batch API works the same way as the Chat Completions endpoint, supporting the same parameters and most of the recent models (gpt-4o, gpt-4o-mini, gpt-4-turbo, gpt-3.5-turbo...).

By using this API, you can significantly reduce costs, so we recommend switching every workload that can happen async to a batch job with this new API.

FAQ

Common questions

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.