CAIRO — Libya’s warring parties have agreed to a cease-fire that took effect after midnight on Saturday, stoking fragile hopes for an end to months of escalating foreign-backed fighting around Tripoli, the capital, that has threatened to push the country into a major conflagration.

The cease-fire was first raised by President Recep Tayyip Erdogan of Turkey and President Vladimir V. Putin of Russia at a meeting in Istanbul last week, ostensibly to end a surge in fighting that had caused thousands of deaths and displaced 300,000 civilians, according to the United Nations.

Turkey and Russia are also protagonists in the fight, backing rival Libyan factions as part of a broader struggle for strategic and economic advantage in the Mediterranean. And it was not immediately clear whether the truce would be respected on the ground, where an array of loosely allied Libyan militias backed by foreign military forces are leading the fight.

A spokesman for Khalifa Hifter, the commander based in eastern Libya whose forces have been laying siege to the capital since April, announced the truce. The beleaguered United Nations-backed government, whose authority is limited to a corner of western Libya, welcomed the move.