where they come from
Each side picks them; that is, the initiator picks its cookies and the responder picks its cookies. After the initial packet (where the initiator doesn't learn the responder cookies yet), each IKE packet will contain both.
how they are generated
However each side wants (as long as it doesn't generate an all-0 value - that value has special meaning). Each side could generate them randomly. A side could generate its cookies with the peer's IP address in it (so it could quickly filter out blind flooding attacks - attacks were bots send out lots of IKE messages). Alternatively, a large scale implementation could embed a 'session identifier' into its cookies (to make lookup faster).
Since the other side doesn't place any significance on the value (other than it being nonzero), it doesn't matter.
why they are used
Several reasons:
The same set of peers could implement several IKE sessions at once (actually, this is quite common); the cookies act as a session identifier.
To thwart any 'replay' style attack, where someone replicates the IKE packets from a previous session (with hopes of fooling the honest peer); because the honest peer will pick a fresh cookie, this doesn't work.
Originally, cookies were introduced into IKEv1/Photuris to thwart blind flooding attacks. Those are no longer a concern in IKEv2 (with the DoS protections built into IKEv2); however the mechanism still exists.