Oh, that's where lua comes in. With current Lua, it would be random, but if we had functions to get our resources, the number of resources around, current number of military units, current number of building, etc, we could make smarter AIs that made alliances based on how well they would profit from it, and set conditions for that.
For example, if you are weak, the AI would probably demand at least some form of payment if they're gonna protect you. But if you are strong, the AI will gladly join you as your ally.