You can basically think of insects like this as organic ASICs. Input in, output out. It's a biological circuit that just has a raw response that's hardcoded in. Kind of like asking how does a computer know to do "MOV". It's baked in to the circuit. Do trial and error trillions of times and some of the circuits end up functioning and survive.