The current explanation for this is an endosymbiotic theory. It is believed that both, chloroplast and mitochondria were once prokaryotic cells (bacteria), living inside larger host cells. The host cells and bacteria formed endosymbiotic relationships long ago. Bacteria inside the host received protection. The aerobic bacteria (oxygen-using) helped the host to exploit O2 for extracting energy and through millions of years became mitochondria. The photosynthetic bacteria have provided crucial nutrients for the host and later became chloroplasts.