Thirty-one Afghan refugees, waving American flags and grinning broadly, were released from federal detention yesterday after up to 18 months in custody for trying to slip into the United States illegally.

"While I was there, I felt a bitterness," said Mohan Singh, 16, gesturing to the Immigration and Naturalization Service detention center. "But now I am free. I am very much thankful."

Singh, like many of the refugees, walked from the center into the arms of waiting relatives. They were ringed by reporters, lawyers, INS officials and politicians who spurred the mass release.

The United Nations estimates that 4.5 million Afghans, about one-third of the population, have fled the Asian nation since Soviet troops entered the country in December 1979.

The INS detained the refugees for trying to enter the country with forged passports or no documents and was seeking to return them to the countries they last lived in, chiefly Pakistan or India.

The INS agreed to the release Thursday after daylong negotiations.

J. Scott Blackman, assistant district director, said the INS would continue to detain illegal immigrants and stressed that the Afghans had been paroled without any rights of citizenship. "They are not here legally," although they will be allowed to remain, he said.