AI Hints
Home›LangChain Tutorial›Settings, Streaming, Batches
LangChain · Lesson 9 of 120

Batch Calls

Many at once.

⏱ 2 min read▶ Video at 8:27🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Riverside Books wants a one line summary for each of its new books. Calling the model one book at a time is slow. Batch sends several requests at once, in parallel.

Batch Calls
From the video: Batch Calls
  • A summary per book
  • One at a time is slow
  • Batch runs them together

Batching requests

Batch takes a list of inputs, and returns a list of replies, in the same order. Behind the scenes, the calls run in parallel. Run it. We get one short description for each of the three books, and the whole batch takes about as long as a single call.

batch.pypython
import time
from langchain.chat_models import init_chat_model

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

books = ["Dune", "Pride and Prejudice", "The Hobbit"]
prompts = [f"Describe the book {b} in under 12 words." for b in books]

start = time.perf_counter()
replies = model.batch(prompts)
for book, reply in zip(books, replies):
    print(f"{book}: {reply.text.strip()}")
print(f"took {time.perf_counter() - start:.1f} s")
Output
Dune: A young noble fights for control of a deadly desert planet.
Pride and Prejudice: Spirited Elizabeth Bennet and proud Mr. Darcy overcome class and
character flaws.
The Hobbit: A homebody hobbit finds courage, battles dragons, and reclaims lost
treasure.
took 1.2 s

Batch tips

A few tips. Results always come back in the same order as the inputs. You can limit how many run at once with max concurrency, in the config, to stay under rate limits. And if one request might fail, return exceptions equals true gives you the error for that item, instead of failing the whole batch.

keyvalue
Ordersame as inputs
max_concurrencylimit parallel calls
return_exceptionsdon't fail everything
Use formany similar jobs

Summary

Batch sends a list of requests in parallel and returns replies in order. Next, counting tokens, and what each call costs.

Key takeaways
  • model.batch([...])
  • Same order back
  • max_concurrency
Next up: Tokens and Usage — counting the cost