execute method
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';
}