KABUL, Afghanistan — President Obama, speaking to an American television audience on Tuesday night from Bagram Air Base, declared that he had traveled here to herald a new era in the relationship between the United States and Afghanistan, “a future in which war ends, and a new chapter begins.”

Mr. Obama’s address, during an unannounced visit to sign a strategic partnership agreement with President Hamid Karzai that sets the terms for relations after the departure of American troops in 2014, was a chance for him to make an election-year case that he is winding down a costly and increasingly unpopular war.

“My fellow Americans,” he said, speaking against a backdrop of armored military vehicles and an American flag, “we’ve traveled through more than a decade under the dark cloud of war. Yet here, in the pre-dawn darkness of Afghanistan, we can see the light of new day on the horizon.”

His speech came as an already difficult relationship with Mr. Karzai has been strained by recent events, including the release of photos showing American soldiers posing with the remains of Taliban insurgents and an American staff sergeant who has been charged in the killing of 16 Afghan civilians. Mr. Obama sought to portray the withdrawal as an unalloyed achievement, though it remains far from certain that the Afghan government can hold its own against the Taliban with reduced American support, or that what were once considered critical American goals here can still be met.