Theory of a two-level system interacting with a degenerate electron gas. I. Partition function.