AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Create_agent: Before_model Hook Returning Jump_to="Model" Raises KeyError Due To Missing Self-Destination In Middleware Edge Path Map

A before_model middleware hook configured with can_jump_to=["model"] that returns {"jump_to":"model"} crashes create_agent at runtime with KeyError because the conditional edge path map omits the hook's own node name, even though the router resolves "model" to it.

highConfidence 95%LangchainAffected V1.3.18

Origin Analysis

In _add_middleware_edge, the model loop entry point is the first before_model node. A guard 'if name != model_destination' prevents that node from being added to the conditional edge's destinations list, but the jump_edge router still maps the literal "model" destination back to that same node. LangGraph then receives a destination (the node's own name) that was never declared in the edge's path map, producing KeyError.
Install langchain 1.3.18 with langchain-core 1.6.1 and langgraph 1.2.11. Define a StubModel, a my_tool, and an AgentMiddleware subclass with a before_model hook decorated with @hook_config(can_jump_to=["model"]) that returns {'jump_to':'model'} on the first call. Call create_agent(model=StubModel(), tools=[my_tool], middleware=[RestartOnce()]) and invoke with a HumanMessage. The graph builds successfully, but invoking raises KeyError: 'RestartOnce.before_model' during branch resolution.

Fixing Code Block

Edge Case Audit

This patch is a one-line logic change in a graph-building helper. While it fixes the exact crash and should not alter the compiled graph for previously working configurations, it may subtly change edge ordering or duplicate elimination if any code relied on the omitted self-destination remaining absent. Verify that all existing middleware combinations still pass tests, especially those with multiple before_model or before_agent hooks. Rollback by reverting the condition to 'if name != model_destination:'. Concurrency and multithreading are not directly impacted because the change is static graph construction.

Ecosystem Topology