RunnableFunction<RunInput extends Object, RunOutput extends Object> constructor
const
RunnableFunction<RunInput extends Object, RunOutput extends Object> ({
- FutureOr<
RunOutput> invoke(- RunInput input,
- RunnableOptions? options
- Stream<
RunOutput> stream(- Stream<
RunInput> inputStream, - RunnableOptions? options
- Stream<
- RunnableOptions defaultOptions = const RunnableOptions(),
A RunnableFunction allows you to run a Dart function as part of a chain.
You can create a RunnableFunction using the Runnable.fromFunction static method.
When you call invoke
on a RunnableFunction, it will invoke the
function, passing the input to it. The output of the function is returned.
Example:
final openaiApiKey = Platform.environment['OPENAI_API_KEY'];
final model = ChatOpenAI(apiKey: openaiApiKey);
final promptTemplate = ChatPromptTemplate.fromTemplate(
'How much is {a} + {b}?',
);
final chain = Runnable.fromMap({
'a': Runnable.fromFunction((
final Map<String, String> input,
final options,
) async {
final foo = input['foo'] ?? '';
return '${foo.length}';
}),
'b': Runnable.fromFunction((
final Map<String, String> input,
final options,
) async {
final foo = input['foo'] ?? '';
final bar = input['bar'] ?? '';
return '${bar.length * foo.length}';
}),
}) |
promptTemplate |
model |
StringOutputParser();
final res = await chain.invoke({'foo': 'foo', 'bar': 'bar'});
print(res);
// 3 + 9 = 12
Implementation
const RunnableFunction({
final FutureOr<RunOutput> Function(
RunInput input,
RunnableOptions? options,
)? invoke,
final Stream<RunOutput> Function(
Stream<RunInput> inputStream,
RunnableOptions? options,
)? stream,
super.defaultOptions = const RunnableOptions(),
}) : _invokeFunc = invoke,
_streamFunc = stream,
assert(
invoke != null || stream != null,
'Either invoke or stream must be provided',
);