RunnableFunction<RunInput extends Object, RunOutput extends Object> constructor

const RunnableFunction<RunInput extends Object, RunOutput extends Object>({
  1. FutureOr<RunOutput> invoke(
    1. RunInput input,
    2. RunnableOptions? options
    )?,
  2. Stream<RunOutput> stream(
    1. Stream<RunInput> inputStream,
    2. RunnableOptions? options
    )?,
  3. 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',
      );