Liu Heita
In 621, Dou, while trying to aid Wang, under siege at Luoyang by the Tang general Li Shimin the Prince of Qin (Emperor Gaozu's son), was defeated and captured by Li Shimin. The Xia officials initially fled back to the Xia capital Ming Prefecture (洺州, in modern Handan as well) subsequently decided to surrender, and Wei followed Pei Ju back to the Tang capital Chang'an. Emperor Gaozu's oldest son Li Jiancheng the Crown Prince had long heard of Wei's talents, and he invited Wei to serve as his librarian. In 622, with Dou's general Liu Heita having risen against Tang and captured most of former Xia territory, Wei and another staff member, Wang Gui, suggested to Li Jiancheng that due to Li Shimin's accomplishments and fame, he posed a threat to Li Jiancheng, and that Li Jiancheng needed some victories of his own—indicating that he should volunteer to attack Liu. Li Jiancheng agreed, and later in 622 crushed Liu's forces. (Liu was betrayed by his own subordinate Zhuge Dewei () in early 623 and turned over to Li Jiancheng; Li Jiancheng killed him.) As the brothers' rivalry intensified over the year, Wei repeatedly suggested to Li Jiancheng that he must act first and kill Li Shimin. Li Jiancheng could not resolve to do so.