Alkaloids like other secondary plant compounds are formed as protection against the ravaging effects of insects, pests etc.
But from common knowledge, some plants naturally at normal circumstance produce it. This means that God has designed such plants for mans use-medicinally and otherwise. Without such plants, life would be miserable.
in brief Alkaloids are either derivatives terben (Isofrens connected) very rare or vast majority are amino acid. The mechanism of synthesis adopted by plants to avoid degradation of amino acids releasing NH3 by which the cytoplasmic and cellular membrane is harmed. This mechanism call detoxification, resemble crystal formation to avoid oxalic and carbonic acids. Since, plant possess no apparatus for excluding toxic by products, as that occurred in animal sweating and urine scavenging bloods from harm debris. Therefore, alkaloids are rarely occurred in animals.