map_reduce() fans out a prompt template over many inputs concurrently, then folds all results into a single answer with a reduce prompt. It is the canonical way to apply the same LLM operation to a list of items and synthesise the outputs.
importasyncioimportosfromexecutionkitimportProvider,map_reduceDOCS=["ExecutionKit ships zero runtime dependencies.","All patterns are async coroutines returning PatternResult.","MockProvider is used in tests to avoid real API calls.",]asyncdefmain()->None:asyncwithProvider(base_url="https://api.openai.com/v1",api_key=os.environ["OPENAI_API_KEY"],model="gpt-4o-mini",)asprovider:result=awaitmap_reduce(provider,inputs=DOCS,map_prompt_template="Extract one key fact from: {item}",reduce_prompt_template=("You have these key facts:\n{mapped_outputs}\n\n""Write a two-sentence executive summary."),)print(result.value)print(result.metadata["map_count"])# 3print(result.metadata["total_calls"])# 4 (3 map + 1 reduce)print(result.cost.llm_calls)# 4asyncio.run(main())
When inputs is empty the map phase is skipped entirely. The reduce step is still called once with {mapped_outputs} replaced by an empty string, allowing the reduce prompt to handle the zero-item case gracefully.
result=awaitmap_reduce(provider,inputs=[],map_prompt_template="Summarize: {item}",reduce_prompt_template="Items: {mapped_outputs}. No items were provided.",)# result.metadata["map_count"] == 0# result.metadata["total_calls"] == 1