KABUL, Afghanistan — Afghanistan swore in Ashraf Ghani Ahmadzai as its second elected president on Monday, embarking on a new era with a national unity government poised to confront a resilient Taliban insurgency by signing an agreement with the United States that would guarantee a continuing American military presence.

As Hamid Karzai left the political stage, the new president was locked into an uneasy partnership with his defeated rival, Abdullah Abdullah, who became the country’s first chief executive. With a hug for the cameras, both sides appeared determined to reach across factions and avoid a descent into an abyss similar to what has happened in Iraq, where the government’s failure to mend lingering sectarian divisions following a full U.S. withdrawal helped give rise to the brutal Islamic State group.

The new Afghan government was expected Tuesday to sign a security agreement that provides a legal framework for the United States to keep about 9,800 troops in the country to train, advise and assist Afghan national security forces after the current international combat mission ends Dec. 31. That number of troops is expected to be cut in half by the end of 2015, and the U.S. would leave only about 1,000 in a security office after the end of 2016.

Karzai, the outgoing president, had refused to approve the deal, which is intended to help Afghan security forces combat the resilient Taliban insurgency.

The Afghan government also is expected to sign an agreement this week with NATO that would outline the parameters of 4,000 to 5,000 additional international troops – mostly from Britain, Germany, Italy and Turkey – to stay in Afghanistan in a noncombat role after the end of this year.

Without a post-2014 residual force, U.S. military officials say there is a risk that the Afghan security force will deteriorate.