question key used by the prompt).
Batching is useful for throughput optimization: the runtime unpacks your list and invokes the chain for each item (typically in parallel), returning a list of outputs that maintain the input order.
How batching works (high level)
- Provide a list of dictionaries. Each dictionary maps prompt variable names to values (e.g.,
{"question": "..."}). - Call
chain.batch(...). The runtime executes the chain once per dictionary in the list. - The return value is a list of outputs in the same order as the input list.
- The runtime usually parallelizes these invocations, so large batches can complete in roughly the same time as a single invocation (subject to concurrency limits, API rate limits, and client/runtime settings).
Example: prompt template + LLM + output parser + batch
The example below demonstrates:- Creating a chat prompt template that expects a
questionvariable. - Composing the prompt with an LLM and an output parser.
- Building a list of input dictionaries.
- Executing the chain via
chain.batch(...)to process inputs concurrently.
Ensure each element in the batch is a dictionary whose keys exactly match the prompt template variable names (for example, use
{"question": "..."} if the template refers to {question}).Key points (quick reference)
Measuring performance: single vs batched runs
To compare single synchronous execution time versus batched execution time, measure wall-clock time for both approaches. The snippet below runs each input individually (synchronously) and then runs the same inputs viachain.batch(...).
chain.run({"question": "..."})) or directly as a string when the chain accepts a single positional argument. Use the form that matches your LangChain runtime version.
Batching and concurrency increase throughput but also increase parallel API usage. Be mindful of rate limits, concurrency caps, costs, and downstream system limits when issuing large batches.
Practical considerations and tips
- Validate input keys: confirm that each dictionary includes exactly the keys referenced by the prompt template.
- Batch size: tune batch sizes to balance latency, throughput, and rate limits.
- Error handling: decide how to handle per-item failures (e.g., retries, partial failures, logging). The runtime may surface errors per-item or for the whole batch depending on implementation.
- Idempotency & costs: repeated or retried batches can increase cost—track requests and consider idempotency keys if supported.
Summary
Batching withchain.batch(...) lets you send multiple prompt-variable dictionaries at once so the runtime can execute them in parallel (subject to concurrency and rate limits). It returns a list of outputs in the same order as the inputs. Use batching to dramatically improve throughput when running many similar invocations.
Further topics you may explore: runnable pass-through, more advanced LCEL concepts, and runtime-specific concurrency configuration.