Have you restarted your Mac lately?
Rebooting is the best first step in troubleshooting.
If a simple reboot of your Mac doesn’t fix things, see if the problem still happens in safe mode. Use a wired USB keyboard for this. If you have the Magic Keyboard, plug that into the Mac with its charging cable.
How to use safe mode on your Mac - Apple Support
Safe mode will often correct weird software behavior by forcing the OS to clear caches, do disk repair and other self-maintenance and housekeeping and temporarily disables third-party mods.
Do the keys work while in Safe mode?
If so, that might be an indication of interference from some installed software when booted normally.
You can exit safe mode by restarting your Mac normally, then reevaluate the problem.
Do you have installed any anti-virus, cleaning/optimizing or VPN software? If so, disable those - better yet, uninstall them, they're not needed. Then restart and see if that has an effect on the problem.