sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[FEATURE] Deterministic resume routing after interrupt() — skip LLM invocation for known responses

Open yananym opened this issue 5 months ago • 3 comments

Problem Statement

When a Strands Graph node calls interrupt() via a tool (e.g., ask_user), the graph pauses and saves state. On resume, the SDK correctly replays the saved tool_use_message and the interrupted tool returns the user's response. However, the tool result is always fed back to the LLM event loop — the model must be invoked to decide the next action.

For deterministic responses (button clicks, "yes"/"no", cancel, option selection from a known list), the next action is knowable without LLM reasoning. There is currently no mechanism to short-circuit the event loop after a tool returns on resume.

Concrete impact:

  • Each unnecessary Bedrock invocation adds ~2-3s latency (TTFT with prompt caching)
  • Simple interactions (consent buttons, cancel, option selection) make up 40-60% of resumes in production workflows but still require full model invocation
  • Workflows with multiple interrupt points accumulate significant latency from these unnecessary round-trips

What we want: A way for a graph node to handle an interrupt resume response deterministically — update state and route to the next node — without invoking the LLM.


Existing Infrastructure

The SDK already has a mechanism that partially addresses this:

request_state["stop_event_loop"] (event_loop.py line 782) — After tools execute, if this flag is set in invocation_state["request_state"], the event loop yields a stop event and returns without invoking the model again. Today this is used by strands_tools.stop and the bidirectional agent's stop_conversation tool.

A tool can already set this today:

@tool(context=True)
def ask_user(tool_context: ToolContext, question: str, options: list[str] = []) -> str:
    response = tool_context.interrupt({"question": question, "options": options})
    if response in options:
        tool_context.invocation_state["request_state"]["stop_event_loop"] = True
    return response

However, this only solves the agent-level problem. The following graph-level gaps remain:

Gap 1: stop_event_loop is semantically wrong for the interrupt-resume case

When an agent's event loop stops via stop_event_loop, it yields EventLoopStopEvent with stop_reason="tool_use" (since tools executed). The graph's _execute_node (line 1060) reads this:

stop_reason = getattr(agent_response, "stop_reason", "end_turn")

If stop_reason is not "interrupt", the node is marked COMPLETED — as if the agent finished its work normally. But that's semantically incorrect here.

The node's stop_reason should remain "interrupt" because the node was interrupted waiting for user input. The user responding with "yes" doesn't mean "the agent finished its reasoning" — it means "the interrupt is resolved." These are different states:

  • stop_reason="end_turn" → agent completed its work
  • stop_reason="interrupt" → agent is waiting for external input
  • What we actually need → "interrupt resolved, route forward with deterministic result, no LLM needed"

Using stop_event_loop conflates "I'm done" with "the interrupt resolved deterministically." This breaks:

  • Session semantics: A node that stopped normally vs. one that resolved an interrupt should have different replay behavior on re-invocation
  • Observability: Tracing should reflect "interrupt resolved without model" not "agent completed normally"
  • Re-invocation safety: If the session is restored, the graph needs to know this node completed via deterministic interrupt resolution, not via normal agent execution

Gap 2: Node result content after early stop may be empty or opaque

When the event loop stops early, the AgentResult contains whatever the model last produced (which on resume from interrupt is... nothing, since the model was never invoked). Downstream nodes receive this via _build_node_input(), which formats "Inputs from previous nodes" from the agent's message content. An empty or tool-result-only message may not provide useful input for edge conditions or downstream nodes that inspect state.results[node_id].

Gap 3: Edge conditions may need the deterministic output

Edge conditions evaluate against GraphState after node completion (_find_newly_ready_nodes calls edge.should_traverse(self.state, ...)). If the deterministic response needs to influence routing (e.g., "yes" goes to node A, "no" goes to node B), the response must be accessible in GraphState or invocation_state. Today there's no convention for how a tool's early-stop result propagates to edge condition context.

Gap 4: Session persistence on resume path

When a node completes after interrupt resume, the session manager persists state.results[node_id]. If the node skipped the LLM, the persisted NodeResult must still be valid and rehydratable via NodeResult.from_dict(). The result's inner AgentResult must serialize correctly even when no model call occurred.


Proposed Solution Paths

Path A: AfterToolCallEvent.stop_event_loop signal (hook-based)

Add a stop_event_loop: bool = False writable field to AfterToolCallEvent. When set by a hook callback, the event loop stops after that tool — same behavior as the request_state flag but with a clean hook contract:

class ResumeRouterHook(HookProvider):
    def register(self, registry: HookRegistry):
        registry.add_callback(AfterToolCallEvent, self.on_after_tool_call)
    
    def on_after_tool_call(self, event: AfterToolCallEvent):
        if event.tool_use.get("name") == "ask_user":
            result_text = event.result.get("content", [{}])[0].get("text", "")
            if result_text in self.known_options:
                event.stop_event_loop = True

Implementation notes:

  • AfterToolCallEvent already has writable fields (result, retry). Adding stop_event_loop follows the same pattern.
  • PR #2178 (open) adds _Interruptible to AfterToolCallEvent for a different purpose (pause). Both could coexist: interrupt() pauses, stop_event_loop terminates the cycle.
  • The event loop (_handle_tool_execution) would check event.stop_event_loop after processing results, same as it checks retry today.

Pros: Clean hook contract. Decouples routing logic from tool implementation. Works with existing hook registration and ordering. Cons: Still agent-level — the same graph-level gaps (2-4) apply. A hook can stop the loop but can't directly set graph-level output or influence edge conditions. Same semantic mismatch as stop_event_loop — the graph still sees a normal agent completion, not a resolved interrupt.


Path B: resume_handler on graph nodes (graph-level primitive)

Allow nodes to register a function that intercepts resume before the agent is invoked at all:

from strands.multiagent import GraphBuilder

def handle_resume(state: GraphState, interrupt_response: Any) -> NodeResult | None:
    """If returns NodeResult, skip the agent entirely.
       If returns None, run the agent normally (existing behavior)."""
    if interrupt_response in state.results.get("_last_options", []):
        return NodeResult(
            result=AgentResult(stop_reason="end_turn", message={"role": "assistant", "content": [...]}),
            execution_time=0,
            status=Status.COMPLETED,
            accumulated_usage=Usage(inputTokens=0, outputTokens=0, totalTokens=0),
            accumulated_metrics=Metrics(latencyMs=0),
            execution_count=0,
        )
    return None

builder = GraphBuilder()
builder.add_node("approval", agent, resume_handler=handle_resume)

Where it hooks in: _execute_node() at line ~1008, after BeforeNodeCallEvent fires but before node.executor.stream_async() is called. On resume (when self._interrupt_state.activated and this node is the interrupted one), the graph calls resume_handler first.

Pros:

  • Cleanest solution for the graph use case — all gaps resolved at one layer
  • No event loop changes needed
  • Agent is never instantiated for deterministic paths (zero model tokens, zero TTFT)
  • The handler produces a full NodeResult, so downstream edges and session persistence work identically to a normal completion
  • Backward compatible (handler is optional, None return = existing behavior)

Cons:

  • New API surface on GraphBuilder.add_node() and GraphNode
  • Handler must construct a valid NodeResult (ergonomic burden on the user)
  • Requires understanding GraphState, NodeResult, and AgentResult internals
  • Doesn't help non-graph use cases (standalone agents with interrupt)

Path C: Hybrid — Path A + simplified Path B

Use AfterToolCallEvent (Path A) for standalone agent use cases, and add a lightweight graph-level resume_handler that returns a simple dict instead of a full NodeResult:

def handle_resume(state: GraphState, interrupt_response: Any) -> dict | None:
    """Return dict to skip agent (dict becomes node output). Return None for normal resume."""
    if interrupt_response in ["yes", "no", "cancel"]:
        return {"user_choice": interrupt_response}
    return None

builder.add_node("approval", agent, resume_handler=handle_resume)

The graph wraps the dict into a synthetic NodeResult internally — the user never constructs one manually.

Pros: Best ergonomics. Covers both graph and agent-level use cases. Minimal user-facing complexity. Cons: Two changes in two layers (event loop + graph). The dict-to-NodeResult conversion needs a defined contract (what does the "output" look like to downstream nodes?).


Use Case

1. Guided workflows with button-based interactions: A workflow presents the user with options ("Choose a provider: A, B, or C"). The user clicks a button. The response is one of the known options — no LLM reasoning is needed to determine the next step.

2. Consent/approval gates: "Do you approve this action? [Yes] [No]" — the routing is completely deterministic based on which button was clicked.

3. Cancel/exit flows: User clicks "Cancel" at any interrupt point. The workflow should immediately route to a cancellation node without invoking the model.

4. Multi-step forms: A workflow collects structured data across multiple interrupt points (name, date, selection). Each response maps directly to a state field and advances to the next prompt — no model reasoning needed between steps.

5. High-throughput production agents: Any scenario where resume latency matters (customer-facing workflows, real-time applications) and the response space is bounded/predictable.


Alternative Solutions (Prior Art)

LangGraph's Command pattern

LangGraph solves this with Command(update=..., goto=...):

from langgraph.types import interrupt, Command

def approval_node(state: State) -> Command[Literal["execute", "cancel"]]:
    answer = interrupt({"question": "Approve?", "options": ["yes", "no"]})
    if answer == "yes":
        return Command(update={"approved": True}, goto="execute")
    else:
        return Command(update={"approved": False}, goto="cancel")

After interrupt() returns, the node function runs Python code that updates state and routes directly to the next node — never invoking an LLM. This is a first-class framework primitive.

Key architectural differences from Strands:

  • LangGraph nodes are callables that return a value (state update or Command) to the graph executor. Even when a node wraps an LLM agent, the node function controls what happens after interrupt() resumes — it can return Command(goto=...) and bypass further LLM calls because the routing decision lives in the node function's code, outside the agent loop.
  • In Strands, the node's executor (agent) owns the full event loop. Once inside agent.stream_async(), there's no escape hatch — the loop runs to completion. The graph has no control point between "interrupt resolved" and "agent finishes."
  • LangGraph's goto does explicit node routing; Strands uses edge conditions with should_traverse()
  • LangGraph has channel-based scheduling with version tracking; Strands uses dependency-based batch execution
  • LangGraph checkpoints after every "superstep" with full channel serialization; Strands persists via SessionManager at node boundaries

Additional Context

Related issues

# Title Relationship
#2178 feat: support interrupts from AfterToolCallEvent Open PR. Adds _Interruptible to AfterToolCallEvent. If merged, Path A builds on the same event class. Not a prerequisite (different signal: pause vs. stop).
#2489 Resume agent loop from pending toolUse messages (TS) Same motivation (skip model on resume) but for TypeScript and session-restore scenarios. Python SDK already has _has_tool_use_in_latest_message().
#2777 Graph checkpoint history and branch-from-checkpoint Complementary — about checkpoint forking, not about what happens within a single resume.
#2404 First-class sub-agent interrupt/resume in multi-agent graphs Overlapping motivation (latency, state loss) but focused on preserving sub-agent execution state across boundaries.
#2243 Tool-level suspend/resume for external async callbacks Different axis — external signal wait, not deterministic routing.

Acceptance criteria

  • [ ] A graph node can handle an interrupt resume response without invoking the LLM
  • [ ] The node's output is valid and usable by downstream nodes and edge conditions
  • [ ] The node's result is persisted correctly via the session manager (serializable NodeResult)
  • [ ] The graph advances to the next node normally after the handler returns
  • [ ] If the mechanism is not configured (or returns None), existing behavior is unchanged (backward compatible)
  • [ ] Works with S3SessionManager and FileSessionManager
  • [ ] Works with existing hook system (BeforeNodeCallEvent, AfterNodeCallEvent still fire)
  • [ ] Telemetry/tracing reflects that the model was not invoked (for observability — execution_count=0, no model spans)

Relevant source locations

File Lines What
strands/event_loop/event_loop.py 280-283 Interrupt state skip logic (replays tool_use_message)
strands/event_loop/event_loop.py 782 stop_event_loop flag check — stops loop without model call
strands/multiagent/graph.py 974-1138 _execute_node() — where resume_handler would intercept
strands/multiagent/graph.py 940-972 _find_newly_ready_nodes() — edge condition evaluation after node completes
strands/multiagent/graph.py 1148-1200 _build_node_input() — how downstream nodes receive prior results
strands/hooks/events.py 177-220 AfterToolCallEvent — writable result and retry fields
strands/multiagent/base.py 44-126 NodeResult — what the graph persists and passes downstream

Prior art comparison matrix

Framework Mechanism LLM-free resume? Granularity
LangGraph Command(goto=...) returned from node function Yes Per-node, inline
Strands (today) interrupt() always resumes into event loop No (undocumented stop_event_loop exists but graph gaps unresolved) N/A
Strands (proposed) Path A-C above Yes Per-node or per-tool, opt-in

References

  • LangGraph Command docs: https://langchain-ai.github.io/langgraph/concepts/human_in_the_loop/
  • LangGraph interrupt/resume: https://langchain-ai.github.io/langgraph/concepts/persistence/#replay

yananym avatar Jun 15 '26 17:06 yananym

The boundary I would preserve is that an interrupt resume response from a bounded UI control is already a decision value, not fresh prompt input. Feeding that value back through the model makes the transition slower, but it also weakens replay semantics because the framework can no longer distinguish "decision consumed" from "model reasoned again after the decision."

I would make the deterministic path bind to a pending interrupt envelope with fields like:

  • interrupt id;
  • node id;
  • tool use id;
  • response schema or option set version;
  • response value or digest;
  • checkpoint or session version;
  • decided_at;
  • resolver identity class;
  • routing outcome.

Then the graph-level invariant is:

  1. A resume handler can short-circuit the model only when the pending interrupt id, tool use id, response shape, and checkpoint version still match.
  2. The interrupt response is consumed once; duplicate or late resumes are refused as stale rather than routed against current state.
  3. The synthetic node result is explicit about deterministic interrupt resolution, not normal model completion.
  4. Edge conditions read a structured output field, not opaque assistant text or an empty model message.
  5. Session persistence stores enough result shape to replay or rehydrate the node without invoking the model.
  6. Telemetry marks the path as model-skipped with zero model usage, while still preserving the user decision and routing result.

The regression I would keep close is: pause at a consent interrupt, persist the session, reload through both file and object-backed session managers, resume with an allowed value, and assert that the next node is selected with no model call. Then repeat with a changed checkpoint, changed option set, duplicate response, and mismatched tool use id; all should fail closed with a stale or invalid resume result.

That keeps the latency win without turning approval or option selection into an untraceable shortcut.

rpelevin avatar Jun 16 '26 00:06 rpelevin

I'd like to contribute a focused Python implementation of deterministic interrupt-resume handling for Graph nodes. I reviewed current main (e519d67) and propose starting with a single pending tool interrupt: validate its response, produce a serializable node result, and continue through existing conditional edges without another model call. Unconfigured or unhandled responses would retain the existing resume path.

The design would also define how the agent's pending tool call and interrupt state are settled, preserve lifecycle hooks and prior usage, and cover file-session restore and invalid/duplicate responses with deterministic tests. I would keep concurrent and nested interrupts out of the initial scope.

Is this still a feature you would accept? Should I start with a design proposal, and is anyone already working on it? I'll wait for maintainer confirmation before implementation.

AI assistance: this investigation and draft were prepared with an AI coding assistant.

Donyes avatar Oct 08 '26 13:10 Donyes

Following up on my proposal above: would a focused contribution for deterministic Graph resume handling be welcome? I'm happy to start with a design proposal and adjust the scope to your preferred approach. Thanks for your time.

AI-assisted draft.

Donyes avatar Oct 21 '26 06:10 Donyes