The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
fix(langchain): handle parallel usage of the todo tool in planning middleware (#34637)
Harrison Chasebda22aa1d9eb
diff --git a/libs/langchain_v1/langchain/agents/middleware/todo.py b/libs/langchain_v1/langchain/agents/middleware/todo.pyindex f34bd42fa5..f3df233021 100644--- a/libs/langchain_v1/langchain/agents/middleware/todo.py+++ b/libs/langchain_v1/langchain/agents/middleware/todo.py@@ -2,12 +2,14 @@from __future__ import annotations-from typing import TYPE_CHECKING, Annotated, Literal, cast+from typing import TYPE_CHECKING, Annotated, Any, Literal, castif TYPE_CHECKING:from collections.abc import Awaitable, Callable-from langchain_core.messages import SystemMessage, ToolMessage+ from langgraph.runtime import Runtime++from langchain_core.messages import AIMessage, SystemMessage, ToolMessagefrom langchain_core.tools import toolfrom langgraph.types import Commandfrom typing_extensions import NotRequired, TypedDict@@ -135,7 +137,9 @@ class TodoListMiddleware(AgentMiddleware):into task completion status.The middleware automatically injects system prompts that guide the agent on when- and how to use the todo functionality effectively.+ and how to use the todo functionality effectively. It also enforces that the+ `write_todos` tool is called at most once per model turn, since the tool replaces+ the entire todo list and parallel calls would create ambiguity about precedence.Example:```python@@ -222,3 +226,79 @@ class TodoListMiddleware(AgentMiddleware):content=cast("list[str | dict[str, str]]", new_system_content))return await handler(request.override(system_message=new_system_message))++ def after_model(+ self,+ state: AgentState,+ runtime: Runtime, # noqa: ARG002+ ) -> dict[str, Any] | None:+ """Check for parallel write_todos tool calls and return errors if detected.++ The todo list is designed to be updated at most once per model turn. Since+ the `write_todos` tool replaces the entire todo list with each call, making+ multiple parallel calls would create ambiguity about which update should take+ precedence. This method prevents such conflicts by rejecting any response that+ contains multiple write_todos tool calls.++ Args:+ state: The current agent state containing messages.+ runtime: The LangGraph runtime instance.++ Returns:+ A dict containing error ToolMessages for each write_todos call if multiple+ parallel calls are detected, otherwise None to allow normal execution.+ """+ messages = state["messages"]+ if not messages:+ return None++ last_ai_msg = next((msg for msg in reversed(messages) if isinstance(msg, AIMessage)), None)+ if not last_ai_msg or not last_ai_msg.tool_calls:+ return None++ # Count write_todos tool calls+ write_todos_calls = [tc for tc in last_ai_msg.tool_calls if tc["name"] == "write_todos"]++ if len(write_todos_calls) > 1:+ # Create error tool messages for all write_todos calls+ error_messages = [+ ToolMessage(+ content=(+ "Error: The `write_todos` tool should never be called multiple times "+ "in parallel. Please call it only once per model invocation to update "+ "the todo list."+ ),+ tool_call_id=tc["id"],+ status="error",+ )+ for tc in write_todos_calls+ ]++ # Keep the tool calls in the AI message but return error messages+ # This follows the same pattern as HumanInTheLoopMiddleware+ return {"messages": error_messages}++ return None++ async def aafter_model(+ self,+ state: AgentState,+ runtime: Runtime,+ ) -> dict[str, Any] | None:+ """Check for parallel write_todos tool calls and return errors if detected.++ Async version of `after_model`. The todo list is designed to be updated at+ most once per model turn. Since the `write_todos` tool replaces the entire+ todo list with each call, making multiple parallel calls would create ambiguity+ about which update should take precedence. This method prevents such conflicts+ by rejecting any response that contains multiple write_todos tool calls.++ Args:+ state: The current agent state containing messages.+ runtime: The LangGraph runtime instance.++ Returns:+ A dict containing error ToolMessages for each write_todos call if multiple+ parallel calls are detected, otherwise None to allow normal execution.+ """+ return self.after_model(state, runtime)diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_todo.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_todo.pyindex 3cea8263e4..ff44c45022 100644--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_todo.py+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_todo.py@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, castimport pytestfrom langchain_core.language_models.fake_chat_models import GenericFakeChatModel-from langchain_core.messages import AIMessage, HumanMessage+from langchain_core.messages import AIMessage, HumanMessage, ToolMessagefrom langchain.agents.factory import create_agentfrom langchain.agents.middleware.todo import (@@ -498,8 +498,282 @@ async def test_custom_system_prompt_async() -> None:# Should use custom prompt in the modified request passed to handlerassert captured_request is not Noneassert captured_request.system_prompt == custom_prompt- # Original request should be unchanged- assert request.system_prompt is None+++def test_parallel_write_todos_calls_rejected() -> None:+ """Test that parallel write_todos calls are rejected with error messages."""+ middleware = TodoListMiddleware()++ # Create an AI message with two write_todos tool calls+ ai_message = AIMessage(+ content="I'll update the todos",+ tool_calls=[+ {+ "name": "write_todos",+ "args": {"todos": [{"content": "Task 1", "status": "pending"}]},+ "id": "call_1",+ "type": "tool_call",+ },+ {+ "name": "write_todos",+ "args": {"todos": [{"content": "Task 2", "status": "pending"}]},+ "id": "call_2",+ "type": "tool_call",+ },+ ],+ )++ state: PlanningState = {"messages": [HumanMessage(content="Hello"), ai_message]}++ # Call after_model hook+ result = middleware.after_model(state, _fake_runtime())++ # Should return error messages+ assert result == {+ "messages": [+ ToolMessage(+ content=(+ "Error: The `write_todos` tool should never be called multiple times "+ "in parallel. Please call it only once per model invocation to update "+ "the todo list."+ ),+ tool_call_id="call_1",+ status="error",+ ),+ ToolMessage(+ content=(+ "Error: The `write_todos` tool should never be called multiple times "+ "in parallel. Please call it only once per model invocation to update "+ "the todo list."+ ),+ tool_call_id="call_2",+ status="error",+ ),+ ]+ }+++def test_parallel_write_todos_with_other_tools() -> None:+ """Test that parallel write_todos calls are rejected but other tool calls remain."""+ middleware = TodoListMiddleware()++ # Create an AI message with two write_todos calls and one other tool call+ ai_message = AIMessage(+ content="I'll do multiple things",+ tool_calls=[+ {+ "name": "some_other_tool",+ "args": {"param": "value"},+ "id": "call_other",+ "type": "tool_call",+ },+ {+ "name": "write_todos",+ "args": {"todos": [{"content": "Task 1", "status": "pending"}]},+ "id": "call_1",+ "type": "tool_call",+ },+ {+ "name": "write_todos",+ "args": {"todos": [{"content": "Task 2", "status": "pending"}]},+ "id": "call_2",+ "type": "tool_call",+ },+ ],+ )++ state: PlanningState = {"messages": [HumanMessage(content="Hello"), ai_message]}++ # Call after_model hook+ result = middleware.after_model(state, _fake_runtime())++ # Should return error messages for write_todos calls only+ assert result == {+ "messages": [+ ToolMessage(+ content=(+ "Error: The `write_todos` tool should never be called multiple times "+ "in parallel. Please call it only once per model invocation to update "+ "the todo list."+ ),+ tool_call_id="call_1",+ status="error",+ ),+ ToolMessage(+ content=(+ "Error: The `write_todos` tool should never be called multiple times "+ "in parallel. Please call it only once per model invocation to update "+ "the todo list."+ ),+ tool_call_id="call_2",+ status="error",+ ),+ ]+ }+++def test_single_write_todos_call_allowed() -> None:+ """Test that a single write_todos call is allowed."""+ middleware = TodoListMiddleware()++ # Create an AI message with one write_todos tool call+ ai_message = AIMessage(+ content="I'll update the todos",+ tool_calls=[+ {+ "name": "write_todos",+ "args": {"todos": [{"content": "Task 1", "status": "pending"}]},+ "id": "call_1",+ "type": "tool_call",+ },+ ],+ )++ state: PlanningState = {"messages": [HumanMessage(content="Hello"), ai_message]}++ # Call after_model hook+ result = middleware.after_model(state, _fake_runtime())++ # Should return None (no intervention needed)+ assert result is None+++async def test_parallel_write_todos_calls_rejected_async() -> None:+ """Test async version - parallel write_todos calls are rejected with error messages."""+ middleware = TodoListMiddleware()++ # Create an AI message with two write_todos tool calls+ ai_message = AIMessage(+ content="I'll update the todos",+ tool_calls=[+ {+ "name": "write_todos",+ "args": {"todos": [{"content": "Task 1", "status": "pending"}]},+ "id": "call_1",+ "type": "tool_call",+ },+ {+ "name": "write_todos",+ "args": {"todos": [{"content": "Task 2", "status": "pending"}]},+ "id": "call_2",+ "type": "tool_call",+ },+ ],+ )++ state: PlanningState = {"messages": [HumanMessage(content="Hello"), ai_message]}++ # Call aafter_model hook+ result = await middleware.aafter_model(state, _fake_runtime())++ # Should return error messages+ assert result == {+ "messages": [+ ToolMessage(+ content=(+ "Error: The `write_todos` tool should never be called multiple times "+ "in parallel. Please call it only once per model invocation to update "+ "the todo list."+ ),+ tool_call_id="call_1",+ status="error",+ ),+ ToolMessage(+ content=(+ "Error: The `write_todos` tool should never be called multiple times "+ "in parallel. Please call it only once per model invocation to update "+ "the todo list."+ ),+ tool_call_id="call_2",+ status="error",+ ),+ ]+ }+++async def test_parallel_write_todos_with_other_tools_async() -> None:+ """Test async version - parallel write_todos calls are rejected but other tool calls remain."""+ middleware = TodoListMiddleware()++ # Create an AI message with two write_todos calls and one other tool call+ ai_message = AIMessage(+ content="I'll do multiple things",+ tool_calls=[+ {+ "name": "some_other_tool",+ "args": {"param": "value"},+ "id": "call_other",+ "type": "tool_call",+ },+ {+ "name": "write_todos",+ "args": {"todos": [{"content": "Task 1", "status": "pending"}]},+ "id": "call_1",+ "type": "tool_call",+ },+ {+ "name": "write_todos",+ "args": {"todos": [{"content": "Task 2", "status": "pending"}]},+ "id": "call_2",+ "type": "tool_call",+ },+ ],+ )++ state: PlanningState = {"messages": [HumanMessage(content="Hello"), ai_message]}++ # Call aafter_model hook+ result = await middleware.aafter_model(state, _fake_runtime())++ # Should return error messages for write_todos calls only+ assert result == {+ "messages": [+ ToolMessage(+ content=(+ "Error: The `write_todos` tool should never be called multiple times "+ "in parallel. Please call it only once per model invocation to update "+ "the todo list."+ ),+ tool_call_id="call_1",+ status="error",+ ),+ ToolMessage(+ content=(+ "Error: The `write_todos` tool should never be called multiple times "+ "in parallel. Please call it only once per model invocation to update "+ "the todo list."+ ),+ tool_call_id="call_2",+ status="error",+ ),+ ]+ }+++async def test_single_write_todos_call_allowed_async() -> None:+ """Test async version - a single write_todos call is allowed."""+ middleware = TodoListMiddleware()++ # Create an AI message with one write_todos tool call+ ai_message = AIMessage(+ content="I'll update the todos",+ tool_calls=[+ {+ "name": "write_todos",+ "args": {"todos": [{"content": "Task 1", "status": "pending"}]},+ "id": "call_1",+ "type": "tool_call",+ },+ ],+ )++ state: PlanningState = {"messages": [HumanMessage(content="Hello"), ai_message]}++ # Call aafter_model hook+ result = await middleware.aafter_model(state, _fake_runtime())++ # Should return None (no intervention needed)+ assert result is Noneasync def test_handler_called_with_modified_request_async() -> None: