createAskUserQuestionTool function

Tool<JsonMap, String> createAskUserQuestionTool(
  1. Genkit ai, {
  2. required ToolRuntime runtime,
})

Builds the tool that asks the user multiple-choice questions.

Implementation

Tool<JsonMap, String> createAskUserQuestionTool(
  Genkit ai, {
  required ToolRuntime runtime,
}) {
  return defineTextTool(
    ai,
    runtime: runtime,
    name: 'ask_user_question',
    description: _description,
    properties: <String, Object?>{
      'questions': <String, Object?>{
        'type': 'array',
        'description': 'One to three questions.',
        'items': <String, Object?>{
          'type': 'object',
          'properties': <String, Object?>{
            'id': stringProperty('Stable identifier used as the key in the answers.'),
            'header': stringProperty('Very short label, at most 12 characters.'),
            'question': stringProperty('The full question, ending with a question mark.'),
            'options': <String, Object?>{
              'type': 'array',
              'description': 'Two to four mutually exclusive choices.',
              'items': <String, Object?>{
                'type': 'object',
                'properties': <String, Object?>{
                  'label': stringProperty('Concise choice text, 1-5 words.'),
                  'description': stringProperty('What choosing this option means.'),
                },
                'required': <String>['label', 'description'],
              },
            },
          },
          'required': <String>['id', 'header', 'question', 'options'],
        },
      },
    },
    required: <String>['questions'],
    run: (input) async {
      final questionsInput = readList(input, 'questions');
      if (questionsInput == null || questionsInput.isEmpty || questionsInput.length > 3) {
        throw const ToolFailure('`questions` must contain between 1 and 3 questions.');
      }

      final questions = questionsInput.map(_parseQuestion).toList();
      runtime.startTool('ask_user_question', 'Waiting for the user to answer');
      final answers = await runtime.askQuestions(questions);
      return jsonEncode(<String, Object?>{'answers': answers});
    },
  );
}