Hosts have numerous defenses against parasites, of which behavioral immune responses are an important but underappreciated component. Here we describe a behavioral immune response that Drosophila melanogaster uses against endoparasitoid wasps. We found that when flies see wasps, they switch to laying eggs in alcohol-laden food sources that protect hatched larvae from infection. This change in oviposition behavior, mediated by neuropeptide F, is retained long after wasps are removed. Flies respond to diverse female larval endoparasitoids but not to males or pupal endoparasitoids, showing that they maintain specific wasp search images. Furthermore, the response evolved multiple times across the genus Drosophila. Our data reveal a behavioral immune response based on anticipatory medication of offspring and outline a nonassociative memory paradigm based on innate parasite recognition by the host.