parseAndExecuteTool function

Future<ToolCallResult> parseAndExecuteTool(
  1. String? modelResponse,
  2. Tools tools
)

Implementation

Future<ToolCallResult> parseAndExecuteTool(String? modelResponse, Tools tools) async {
  if (modelResponse == null || modelResponse.trim().isEmpty) {
    return ToolCallResult(toolCalled: false);
  }

  try {
    final jsonBlocks = _extractJsonBlocks(modelResponse);

    for (final jsonBlock in jsonBlocks) {
      try {
        final response = jsonDecode(jsonBlock) as Map<String, dynamic>;
        final toolCalls = response['tool_calls'] ?? response['tool_call'];

        if (toolCalls != null && toolCalls is List && toolCalls.isNotEmpty) {
          final toolCall = toolCalls.first as Map<String, dynamic>;
          final toolName = toolCall['name'] as String;
          final arguments = toolCall['arguments'] as Map<String, dynamic>;

          final toolOutput = await tools.execute(toolName, arguments);

          return ToolCallResult(
            toolCalled: true,
            toolName: toolName,
            toolInput: arguments.map((k, v) => MapEntry(k, v.toString())),
            toolOutput: toolOutput.toString(),
          );
        }
      } catch (e) {
        continue;
      }
    }

    return ToolCallResult(toolCalled: false);
  } catch (e) {
    return ToolCallResult(toolCalled: false);
  }
}