4. Given real numbers $x, y, z$ satisfy
$$
\left\{\begin{array}{l}
x+y=z-1, \\
x y=z^{2}-7 z+14 .
\end{array}\right.
$$

Question: What is the maximum value of $x^{2}+y^{2}$? For what value of $z$ does $x^{2}+y^{2}$ achieve its maximum value?
Prompt: Example 6. From the problem, we know that $x$ and $y$ are the two real roots of the equation
$$
t^{2}-(z-1) t+z^{2}-7 z+14=0
$$

By the discriminant $\Delta \geqslant 0$, we get
$$
3 z^{2}-26 z+55 \leqslant 0 \text {. }
$$

Solving this, we get $\frac{11}{3} \leqslant z \leqslant 5$.
$$
\begin{array}{l}
\text { Also, } x^{2}+y^{2}=(x+y)^{2}-2 x y \\
=(z-1)^{2}-2\left(z^{2}-7 z+14\right) \\
=(z-6)^{2}+9,
\end{array}
$$

Therefore, when $z=5$, the maximum value of $x^{2}+y^{2}$ is 9.