Aggressors: Ancient Rome

AI is taking into consideration the statistics about relative power (similarly to human player) which you can see in the diplomacy window.
Of course if a player is weak, AI will not be keen to become a member of a confederation/federation however if players share the same enemies, relationships do improve and eventually can get even to a BiA.

The “enemy of my enemy is my friend” is indeed implemented in AI but it varies quite a lot how quickly the nations get closer to each other. It might be long lasting previous war, dishonorable military actions, inconsistency in foreign relations (one player is in great relation with another player and the second player hates that another player). etc.
I am sure that Carthage (if it is already threatened by Rome) would get eventually closer to all Roman enemies, but I think the bit problem was Ptolemaic empire in your case. It seems like they are actually fighting more them than Romans:)