Mem-$π$: Adaptive Memory through Learning When and What to Generate — ThinkLLM