execute method

Future<String> execute({
  1. required String task,
  2. required String systemPrompt,
  3. Map<String, dynamic>? context,
})

Implementation

Future<String> execute({
  required String task,
  required String systemPrompt,
  Map<String, dynamic>? context,
}) async {
  _logger.info('');
  _logger.info('${lightCyan.wrap('πŸ€– Starting AI task execution...')}');
  _logger.detail('${darkGray.wrap('Task:')} $task');

  _conversationHistory.add(ChatMessage.humanText(task));

  int currentTurnIterations = 0;
  bool taskCompleted = false;

  while (currentTurnIterations < maxIterations && !taskCompleted) {
    currentTurnIterations++;
    _totalIterations++;

    _logger.info('');
    _logger.info('${darkGray.wrap('─' * 60)}');
    _logger.info(
        '${lightYellow.wrap('πŸ”„ Iteration $currentTurnIterations/$maxIterations')}');

    final progress = _logger.progress('${lightCyan.wrap('Thinking')}');

    try {
      final response = await _llm.invoke(
        PromptValue.chat([
          ChatMessage.system(_buildSystemPrompt(systemPrompt, context)),
          ..._conversationHistory
        ]),
      );

      progress.complete('${lightGreen.wrap('βœ“')} Response received');

      final aiMessage = response.output;
      _conversationHistory.add(aiMessage);

      if (aiMessage.contentAsString.isNotEmpty) {
        _logger.detail(
            '${darkGray.wrap('AI Response:')} ${aiMessage.contentAsString.substring(0, aiMessage.contentAsString.length > 100 ? 100 : aiMessage.contentAsString.length)}${aiMessage.contentAsString.length > 100 ? '...' : ''}');
      }

      if (aiMessage.toolCalls.isNotEmpty) {
        _logger.info(
            '${lightMagenta.wrap('πŸ”§ Tool calls detected:')} ${aiMessage.toolCalls.length} tool(s)');

        final toolResult = await _handleToolCalls(aiMessage.toolCalls);

        if (toolResult.taskCompleted) {
          _conversationHistory.addAll(toolResult.messages);
          _logger.info('');
          _logger
              .info('${lightGreen.wrap('βœ“ Task completed successfully!')}');
          _logger.detail(
              '${darkGray.wrap('Total iterations:')} $currentTurnIterations');
          return toolResult.finalAnswer!;
        }

        _conversationHistory.addAll(toolResult.messages);
        continue;
      }

      _logger.info('');
      _logger.info('${lightGreen.wrap('βœ“ Task completed!')}');
      _logger.detail(
          '${darkGray.wrap('Total iterations:')} $currentTurnIterations');
      return aiMessage.contentAsString;
    } catch (e) {
      progress.fail('${red.wrap('βœ—')} Error occurred');
      _logger.err('Error in iteration $currentTurnIterations: $e');
      rethrow;
    }
  }

  if (currentTurnIterations >= maxIterations) {
    _logger.warn('${yellow.wrap('⚠')} Maximum iterations reached');
    return 'I reached the maximum number of iterations ($maxIterations). Try rephrasing your question.';
  }

  return 'Task completed';
}