That's the kind of thing safety maps are designed for (see
here and
here). Rather than pathfinding away from the player (as in those examples), it would pathfind away from a combination of hostile creatures and environmental dangers. Once the NPC is in a tile it judges to be safe, and isn't panicked, its normal AI can take over again.
The same code could also make magpies much more difficult to track down. If that's not how they already work.