Skip to content

batch 并发分支

batch 用于把多个互相独立的任务并发执行,再把结果汇合回主链路。

场景、命题与解决

场景:一次请求需要并行调用多个服务或工具。
命题:串行执行会带来线性延迟。
解决:用 batch 扇出并发任务,自动汇合结果。

python
import asyncio
from agently import TriggerFlow, TriggerFlowEventData

flow = TriggerFlow()

@flow.chunk("one")
async def one(data: TriggerFlowEventData):
  await asyncio.sleep(0.01)
  return f"one:{data.value}"

@flow.chunk("two")
async def two(data: TriggerFlowEventData):
  await asyncio.sleep(0.02)
  return f"two:{data.value}"

flow.batch(one, two).end()
result = flow.start("X")
print(result)

输出:

text
{'one': 'one:X', 'two': 'two:X'}