EXCLUSIVE

Chief Keef is damn lucky cops were in his neighborhood, and caught 3 alleged burglars red-handed -- but not before one of them opened fire ... TMZ has learned.

The suspects hopped a wall and threw bricks to break a window at the San Fernando Valley home Sunday around 11:15 PM ... according to law enforcement sources. We're told at least one of them got into the home, and was making off with some of the rapper's loot.

The bad news for the bad guys is LAPD had plainclothes officers patrolling the area due to the rash of burglaries lately. We're told cops intervened to thwart the burglary, and one suspect fired a shot -- which didn't hit anyone -- and then the chase was on. Officers nabbed 2 of the perps, but one managed to flee in a getaway car.

Keef, btw, was home during all of this. Cops went to the house and spoke to him afterward. We're told he had no idea the suspects had gotten into the home.