The Mongol Empire conquered the Qara Khitai in the years 1216-1218 AD. Prior to the invasion, war with the Khwarazmian dynasty and the usurpation of power by the Naiman prince Kuchlug had weakened the Qara Khitai. When Kuchlug besieged Almaliq, a city belonging to the Karluks, vassals of the Mongol Empire, Genghis Khan dispatched a force under command of Jebe to pursue Kuchlug. After his force of 30,000 was defeated by Jebe at the Khitan capital Balasagun, Kuchlug faced rebellions over his unpopular rule, forcing him to flee to modern Afghanistan, where he was captured by hunters in 1218. The hunters turned Kuchlug over to the Mongols, who beheaded him. Upon defeating the Qara Khitai, the Mongols now had a direct border with the Khwarazmian Empire, which they would soon invade in 1219.. Which happened first, war with the Khwarazmian dynasty, or the invasion by the Mongols?