4. Let the terms of the sequence $\left\{a_{n}\right\}$ be positive numbers, and the sum of the first $n$ terms $S_{n}$ satisfies $S_{n}=$ $\frac{1}{2}\left(a_{n}+\frac{1}{a_{n}}\right)$, then $a_{n}=$ $\qquad$ .
$$
a_{1}^{2}=1 \Rightarrow a_{1}=1, a_{2}^{2}+2 a_{2}-1=0 \Rightarrow a_{2}=\sqrt{2}-1, a_{3}^{2}+2 \sqrt{2} a_{3}-1=0 \Rightarrow a_{3}=\sqrt{3}-\sqrt{2} \text {, }
$$

Conjecture $a_{n}=\sqrt{n}-\sqrt{n-1}$.
If the conclusion holds for $n \leqslant k$, then $S_{k}=\sqrt{k} \Rightarrow 2 \sqrt{k}=a_{k+1}+\frac{1}{a_{k+1}} \Rightarrow a_{k+1}^{2}+2 \sqrt{k} a_{k+1}-1=0$ $\Rightarrow a_{k+1}=\sqrt{k+1}-\sqrt{k}$, which means the conclusion also holds for $n=k+1$. In summary, $a_{n}=\sqrt{n}-\sqrt{n-1}$.