Asterisk as a gateway

Hi, I want to be able to use asterisk as a gateway, asterisk should decide which provider should a call go to based on a QoS / cost relation.

I believe this is possible, and may be achievable by customizing the AGI script that provides B2BUA functionality, but other than that I don’t have a clue, anyone can give any pointers or help on this matter?