Batching LLM API Requests: How to Combine Calls and Save
Summary
Batching LLM API requests allows combining several independent calls into one, reducing costs and service load.
When Batching is Needed
Batching is effective when an application sends many short, similar requests: product classification, entity extraction, meta-tag generation. Combining into one request reduces the number of HTTP calls and overall cost, as providers often charge less for a batch.
Approaches to Batching
1. Native Provider Batching
Some APIs support passing an array of prompts in one request. Example for DeepSeek API:
import openai
client = openai.OpenAI(api_key="YOUR_API_KEY", base_url="https://api.deepseek.com")
prompts = [
"Classify product: 'Nike Air Shoes'",
"Classify product: 'Cotton T-shirt'",
"Classify product: 'Samsung Galaxy Smartphone'"
]
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": "\n\n".join(prompts)}]
)
2. Batch Processing Through Queue
If the API does not support batches, use a queue and send requests with a delay. This reduces the risk of exceeding rate limit.
import time
import queue
import threading
import openai
client = openai.OpenAI(api_key="YOUR_API_KEY")
q = queue.Queue()
results = {}
def worker():
while True:
item = q.get()
if item is None:
break
idx, prompt = item
try:
resp = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": prompt}]
)
results[idx] = resp.choices[0].message.content
except Exception as e:
results[idx] = f"Error: {e}"
finally:
q.task_done()
for i, p in enumerate(prompts):
q.put((i, p))
threads = [threading.Thread(target=worker) for _ in range(3)]
for t in threads:
t.start()
q.join()
for t in threads:
q.put(None)
Batch Formation Strategies
| Strategy | Description | When to Use |
|---|---|---|
| By Count | Fixed number of prompts (e.g., 10) | Similar tasks |
| By Tokens | Total prompt size does not exceed limit | Varying prompt lengths |
| By Time | Send every N seconds | Stream processing |
Handling Errors in Batch
When combining requests, an error in one element should not break the entire batch. Separate responses by index and handle each individually. Use retries with exponential delay for failed elements.
import time
def process_batch(prompts, max_retries=3):
results = []
for idx, prompt in enumerate(prompts):
for attempt in range(max_retries):
try:
resp = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": prompt}]
)
results.append(resp.choices[0].message.content)
break
except Exception:
if attempt == max_retries - 1:
results.append(None)
else:
time.sleep(2 ** attempt)
return results
Cost and Performance
Batching reduces the number of HTTP requests, lowering overhead and the risk of blocking. However, the total response time may increase if the batch is too large. Experimentally choose batch size based on limits of the provider.
Conclusion
Batching is a simple way to optimize LLM API usage. Start with native batching if supported, otherwise use a queue with parallel workers. Always handle errors for each element separately.