Antimicrobial peptides are host-encoded antibiotics that combat invading microbes and help shape the microbiome in plants and animals. However, little is known about how the host antimicrobial peptide repertoire is evolutionarily adapted to its microbiome. Here we characterize the function and evolution of the Diptericin antimicrobial peptide family of Diptera. Using mutations affecting the two Diptericins (Dpt) of D. melanogaster, we reveal the specific role of DptA against the pathogen Providencia rettgeri and DptB against the gut mutualist Acetobacter. Strikingly, presence of DptA- or DptB-like genes across Diptera correlates with the presence of Providencia and Acetobacter in their environment. Moreover, presence of DptA- and DpB-like genes is sufficient to predict host resistance against infection by these bacteria across a broad range of fly species. Our study explains the evolutionary logic behind the bursts of rapid evolution of an antimicrobial peptide family, and reveals how the host immune repertoire adapts itself to changing microbial environments.