"America's commitment to the people of Afghanistan will endure," he pledged.
Speaking to troops on this sprawling military base, Obama said the war had reached a pivotal point, with Afghan forces assuming primary responsibility for their country's security.
While many of the 32,800 US forces now in Afghanistan will leave in the coming months, Obama said a continued military presence could help protect gains made during nearly 13 years of fighting.
Obama appeared optimistic that the Afghan government soon would sign a bilateral security agreement allowing the US to keep some forces in the country to train Afghans and launch counterterrorism operations.
More From This Section
He has been considering keeping up to 10,000 troops in Afghanistan and said he would announce his plans shortly.
That announcement could come as early as Wednesday, when Obama delivers the commencement address at the US Military Academy at West Point, New York.
Obama secretly arrived at Bagram Air Field, the main US base in Afghanistan, under the cover of darkness for his first trip to the war zone since 2012. He was spending just a few hours on the base and had no plans to go to Kabul, the capital, to meet with Hamid Karzai, the mercurial president who has had a tumultuous relationship with the White House.
After an overnight flight from Washington, Obama attended a briefing with US officials. He said that as he entered the briefing room, he saw a poster of the Twin Towers destroyed in the 2001 terrorist attacks.
"It's a reminder of why we're here," he said.
This was Obama's fourth visit to Afghanistan as president, but his first since winning re-election in 2012.