工作流-并行工作流

流程说明

  1. 用户输入input数组对应需要并行执行一系列任务, 适用于所有的任务的prompt, 以及线程池的数量
  2. 将每个input并行化运行LLM
  3. 等待所有的运行完毕后返回

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public List<String> parallel(String prompt, List<String> inputs, int nWorks) {
ExecutorService executor = Executors.newFixedThreadPool(nWorkers);

try {
List<CompletableFuture<String>> futures = input.stream()
.map(input -> CompletableFuture.supplyAsync(() 0> {
try{
return chatClient.prompt(prmopt + "\nInput: " + input).call().content();
} catch (Exception e) {
throw new RuntimeException("Failed to process input: " + input, e);
}
}, executor))
.collect(Collectors.toList());

// 等待所有的任务结束
CompletableFuture<Void> allFutures = CompletableFuture.allof(
futures.toArray(CompletableFuture[]::new));
allFutures.join();

return futures.stream()
.map(CompletableFuture::join)
.collec(Collectors.toList());
}
}

适用场景

当拆分后的子任务可以并行化以提高速度的时候, 或者需要多个视角或尝试来获取更高置信度的结果的时候. 涉及到多方面考量的复杂任务的时候, 每个考量都由单独的LLM调用处理, LLM的表现会更好

原文:

When to use this workflow: Parallelization is effective when the divided subtasks can be parallelized for speed, or when multiple perspectives or attempts are needed for higher confidence results. For complex tasks with multiple considerations, LLMs generally perform better when each consideration is handled by a separate LLM call, allowing focused attention on each specific aspect.

  • 投票场景, 多次运行相同的任务来获得不同的输出
  • 切分: 将并行化的任务交给不同的LLM来执行, 比如自动评估的时候, 或者防护机制, 一个LLM处理用户的查询, 另一个模型沙宣不适当的请求和内容