The key is to be warm, firm, and frame your exit around your own needs or a prior commitment, making it seem natural rather than a rejection.
You can start with a little bit of appreciation or validation for the chat, even if it’s a small white lie. Something like, “It’s been so great catching up with you,” or “I’ve really enjoyed hearing your thoughts on this.” This softens the transition.
Then, gently introduce your reason for needing to go. The best reasons are mundane, believable, and hard to argue with. You could mention a simple task, like, “Ah, this reminds me, I need to run and send a quick email before I forget,” or “I should probably get back to that report so I don’t hold up the team.”
Another very polite way is to frame it as being considerate of their time. Saying, “Well, I don’t want to monopolize all your time, so I’ll let you go,” is a classic because it makes you seem thoughtful.
You can also combine this with body language. Start to gently shift your posture, take a small step back, or glance in the direction you need to go as you say, “Anyway, I should let you get on with your day. It was wonderful seeing you!”

Stephen, thanks for sharing.