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 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 timefrom langchain.chat_models import init_chat_modelmodel = 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
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.