How to serve AVIF with WEBP/JPG fallback in right size site wide automatically?

I’m looking for a solution to use images created with fx Shortpixel or another image optimizer on my site without going through a CDN. I’d like function that serves the correct format and size according the the browsers compatability and viewport. I’ve found this guide, but it doesn’t include more compressed formats like AVIF / WEBP (neither does it seem seem to automatically serve the right size)…