Skip to content

Commit

Permalink
fix: RunnableMap doesn't invoke multiple Runnables in parallel (#649)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmigloz authored Feb 10, 2025
1 parent 5085ea4 commit fc722d8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
10 changes: 5 additions & 5 deletions packages/langchain_core/lib/src/runnables/map.dart
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,16 @@ class RunnableMap<RunInput extends Object>
final RunInput input, {
final RunnableOptions? options,
}) async {
final output = <String, dynamic>{};

await Future.forEach(steps.entries, (final entry) async {
output[entry.key] = await entry.value.invoke(
final futures = steps.entries.map((entry) async {
final result = await entry.value.invoke(
input,
options: entry.value.getCompatibleOptions(options),
);
return MapEntry(entry.key, result);
});

return output;
final results = await Future.wait(futures);
return Map.fromEntries(results);
}

@override
Expand Down
28 changes: 28 additions & 0 deletions packages/langchain_core/test/runnables/map_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,34 @@ void main() {
);
});

test('RunnableMap runs tasks in parallel', () async {
final longTask = Runnable.fromFunction(
invoke: (_, __) async {
await Future<void>.delayed(const Duration(seconds: 2));
return 'long';
},
);
final shortTask = Runnable.fromFunction(
invoke: (_, __) async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'short';
},
);

final chain = Runnable.fromMap({
'long': longTask,
'short': shortTask,
});

final stopwatch = Stopwatch()..start();
final result = await chain.invoke({});
stopwatch.stop();

expect(stopwatch.elapsed, lessThan(const Duration(seconds: 3)));
expect(result['long'], 'long');
expect(result['short'], 'short');
});

test('Streaming RunnableMap', () async {
final prompt1 = PromptTemplate.fromTemplate('Hello {input}!');
final prompt2 = PromptTemplate.fromTemplate('Bye {input}!');
Expand Down

0 comments on commit fc722d8

Please sign in to comment.