Bti - use it preemptively whether you have a problem or not, then you never have a gnat problem... Can stop using it 2-3 weeks after getting the medium wet -- that timer resets with any transplant (new medium added)
in north america the common brand is "Mosquito Bits" or "Mosquito Dunks" - whether you top dress or pit some in a reservoir matter of choice.
it's a bacterica that kills the larva. It or a variation of it has been used on food crops for 100+ years? A very long time. It's safe.
Bacillus thuringenisis (israelis subspecies) -- i probably spelled that wrong. Google can fix the spelling. Doesn't have to be 'mosquito bits' brand.
This stuff often comes from the store in the soil... nothing you can really do about that. Find a store that doesn't put stock outside, but even then it can get infested during transportation to that store. If you use it mid-infestation rather than from day 1, it will take 2-3 weeks to clear up the problem.
Adult gnats are annoying and obviously reproduce, but they aren't the stage of life that is damaging your plants.. the larva eat the roots.
Midinfestation - kill with bti and sticky traps... kill from both ends of life cycle.
If you use it from day 1, it'll kill anything before it starts... if you don't see gnats after ~3-4 weeks, you can cease using the BTI. If you had an infestation, i'd continue to use it until the end of the grow as that is a different set of circumstances.
gnats can be avoided ~100% ... and it's cheap to do so.