I'm not entirely sure, but I think it happens automatically if you are on the page where you need to input the OTP and wait for the small pop-up dialogue to appear asking to "fill XXXXXXX from Messages" and click to fill. I also think it only happens when I am using Safari and not another browser.
I suspect that it only automatically deletes the OTP SMS in such a case because macOS "knows" the OTP has just been "consumed" and is no longer a valid message. Filling seem to work from mail too, although I can't recall if there is an autodelete on email OTP.
I cannot recall having ever set that deliberately, and I do know of cases - for example where the SMS was delayed and I switched to Messages to see if I had just missed it, only for it to come in - where the pop-up subsequently didn't appear and the SMS wasn't auto-deleted.
Seems like WebKit manages that in the background and is just smart enough to recognize a particular OTP workflow between Safari and Messages or Mail.
But to be fully transparent, most of my accounts either use authenticator generated TOTP or have moved to Passkeys, so I only see this behaviour on a literal handful of sites.