← Back to Blog

How to handle MFA in LangChain agents without losing your state

Author
Sarah Chen
October 24, 2023

It's the nightmare scenario for every AI engineer: Your LangChain agent has been running for 45 minutes. It has generated code, analyzed data, and formulated a plan. It reaches Step 47—executing a database migration.

The database requires MFA. The API returns a 401 Unauthorized with an MFA challenge.

Your LangChain executor throws an error. The process exits. You lose 45 minutes of context, tokens, and compute.

The Naive Approach (Try/Catch)

Most developers try to wrap their tools in a try/catch block and use time.sleep() while they manually send an email to an admin. This blocks the main thread, wastes compute, and usually times out anyway.

The Suspend-and-Resume Architecture

To fix this, you need an architecture that supports pausing execution, serializing the state to a database, and waking up via a webhook when the human responds.

With Nayker, this is handled automatically via the Nayker SDK. When a tool requires approval, Nayker throws a specific NaykerApprovalPending exception. You catch this exception, serialize the LangChain memory, and exit safely.

try:
    agent_executor.invoke({"input": "run migration"})
except NaykerApprovalPending as e:
    # Save memory to Redis
    save_state(session_id, agent_executor.memory)
    # The Nayker infrastructure is currently pinging the admin in Slack

When the admin clicks "Approve" in Slack, Nayker fires a webhook to your server, you deserialize the memory, and resume the chain exactly where it left off.