Jeremiah received the LORD's word after Nebuzaradan the captain of the special guard had released him from Ramah. He had been bound in chains there along with all the other detainees from Jerusalem and Judah who were being sent off to Babylon.
References for Jeremiah 40:1
The captain of the special guard located Jeremiah and said to him, "The LORD your God declared that a great disaster would overtake this place.
Now the LORD has made it happen. He has done just as he warned because all of you have sinned against the LORD and haven't obeyed him. That's why this has happened to you.
But I'm setting you free from the chains on your hands. If you would like, come with me to Babylon, and I'll take care of you. If you would rather not come with me, that's fine too. Now, the whole land lies before you; go wherever you want.
If you decide to remain here, stay with Gedaliah, Ahikam's son and Shaphan's grandson—the Babylonian appointee in charge of the cities of Judah. Stay with him and the people he rules or go wherever you want." Then the captain of the special guard gave him ample provisions and let him go.
References for Jeremiah 40:5
Jeremiah went to Gedaliah, Ahikam's son at Mizpah, and he stayed with him and the people who remained in the land.