There are chemicals in those bags that go through a reaction and make heat and cold. Chemists sat in labs with a bunch of chemicals and figured out the best ones to use for those packs. The idea behind those reactions is that chemical bonds store a lot of energy. If you break those bonds, heat is given off. Sometimes when you make bonds, you need a lot of heat, that's when everything around the molecules gets really cold, the heat is sucked out of the area.
Bonds are energy.
Some store more energy than others. It's a pretty simple idea. You think of heat, you think of fire. You think of cold, you think of an ice cube. Heat has a lot of kinetic energy and gives it away, cold doesn't have much and absorbs energy from the area.