The present invention provides a method for improving the quality of a formation fluid sample by taking the sample at a time when the formation fluid composition contains the most favorable portion of hydrocarbons. This task is accomplished by determining in real-time, the composition of the fluid flowing into a downhole tool from the formation. This method determines the optical density of the fluid as the fluid flows through the tool. An optical spectrum is generated from the density measurement. The optical spectrum is compared to a composite spectrum generated from a database of known fluid samples. As a result of the comparisons, there is a determination of the derivations between corresponding features of the two spectra. Adjustments are made to the components of the composite spectrum until the deviations between the two spectra are at an acceptable minimum. Determinations of the fluid composition are made from the composition of the composite spectrum at the minimum deviation. The sampling process begins when the fluid composition has a desirable fractional component of hydrocarbons in the fluid.