All I know is that the valves open at low speed or when decelerating, and close at high speed or when accelerating. How do they prevent the compressor from stall or surge?
Valves open at low speed to prevent the blades to stall. At low spool speed, or a low power setting (low power setting => less fuel added to the cycle => less power in the turbine and as such less power available for the compressor), the volumetric flow through the fixed geometry compressor passage becomes too large (with respect to the design value, the compression is less at lower speed), blow-off of some of the air reduces the volumetric flow downstream of the bleed ports.
This can be explained with the so called velocity triangles/diagrams of the compressor:
The increase of the axial speed through the compressor (Uri increases) while the spool speed decreases (ωr decreases) causes the flow Vri angle (Uri - Vri) to become less steep and cause the flow to stall reducing the working of the compressor and blocking the flow passage; this is called surge. Blow-off of the air reduces the Uri flow velocity to prevent the compressor blades from stalling. Some compressors can change the geometry of the stator vanes to adjust for the change in inflow angle, this is referred to as Variable Stator Vanes, which extend the operating range. Bleed-off is the last resort to prevent surge.
This can be easily visualized by simulation of a gas turbine. The following example shows a gas turbine steady-state performance sweep (reduction of fuel) of a typical helicopter turboshaft engine plotted in the compressor characteristic. The dashed simulation does not incorporate a bleed schedule and crosses the surge line on the left (since this is a simulation with extrapolated map characteristics, this is mathematically possible, but not in real life, the compressor would stall and airflow would stagnate), the solid blue line represents the performance where a surge margin of 10 % is maintained by bleeding off compressor air (hence the parallel operating line region at low power).
The image shows the steady state performance/equilibrium line in the compressor characteristic, the transient working line would show a way different profile. The reason that bleed-off may be interesting for spooling up (more fuel added for a higher power setting) is that an instant increase in fuel will cause the amount of reaction product to increase causing the pressure inside the gas turbine to rise at the same spool speed (due to the inertia, the spool spooling up is relatively slow) which results in the working point to go to the surge line (following the constant spool speed line). Usually the amount of fuel is limited by the controller which gradually adds the fuel. If the working point gets to close to the surge line, bleeding off compressor air will prevent the compressor to surge.