What should one do if one finds oneself unsure in the
middle of the prayer how many raka’at one has prayed?

If a person falls into doubt as to whether he prayed, e.g., three of
four raka‘at, he should consider the most likely case. However, if he
cannot put more weight to one of the two, he should assume what he
is certain of and that is lesser amount, and make the prostrations of
forgetfulness (sujood ul-sahw). The evidence is the hadith narrated
by Abu Sa‘eed Al-Khudri (may Allah be please with him), who said:

The Prophet
(peace be upon him) said: If one of you
has doubts during his prayer and he does not recall how many
rak‘at he has prayed, whether three or four, then he can put an
end to his doubt by praying according to what he was certain of
(the lesser amount) and then making two sujood before the
salaam. If it turns out that he had prayed five raka‘at, the two
sujood would make it even. Whereas if he ended up completing
his four raka‘at , they would be in defiance of the Satan.

  (Sahih Muslim, No. 571)