Code Tidy up and API

Moved shared code into ai package for better organization and for API
adaptions later.