Cats and many other animals possess zoopharmacognosy. That's just a fancy word meaning that they can sense what plants have medicinal benefits for them. It sure is fun to say. I have watched my own cat do this many times. She has had problems with asthma and when she did, chose to eat hackberry leaves and ragweed, both of which are good for respiratory health and allergies. My dog does this too. She's been going around my yard eating goldenrod and hackberry, again, for her allergies. She even ate white vervain, which is intensely bitter tasting and also a nervine, which is interesting, since she has anxiety. There are tons of other instances of animals doing this if you observe animals with access to plants or if you read about it.
I wonder if cats and dogs eating grass is them trying to exercise their zoopharmacognosy, but because most often, people have monocultures of grass and/or tend to keep their animals away from any unknown plants, they just settle for grass? Most people aren't growing lots of wild or medicinal plants in their yard, so most cats and dogs probably don't have other options.
You can give your cat the chance to practice this inside by laying out some fresh or dried cat safe herbs for them on a towel or blanket with some space between each herb, that way they can investigate and choose what they like. Here's a website with a little more information and lists of cat safe herbs to offer: https://drjudymorgan.com/blogs/blog/supporting-your-cats-healing-through-self-selection-principles
I'm sure something similar could be done for dogs. Or of course, if you have a garden full of medicinal plants and you know what is safe for your pet, you can just walk around with them and see what they choose. I think we can learn a lot about our animal companions and plants this way!