The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
fix(langchain): avoid UnboundLocalError when no AIMessage exists (#34816)
Saakshi Gupta91bb474dbc74
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.pyindex b2032add8b..7f9979fa8f 100644--- a/libs/langchain_v1/langchain/agents/factory.py+++ b/libs/langchain_v1/langchain/agents/factory.py@@ -1556,18 +1556,23 @@ def _resolve_jump(def _fetch_last_ai_and_tool_messages(messages: list[AnyMessage],-) -> tuple[AIMessage, list[ToolMessage]]:- last_ai_index: int- last_ai_message: AIMessage+) -> tuple[AIMessage | None, list[ToolMessage]]:+ """Return the last AI message and any subsequent tool messages.+ Args:+ messages: List of messages to search through.++ Returns:+ A tuple of (last_ai_message, tool_messages). If no AIMessage is found,+ returns (None, []). Callers must handle the None case appropriately.+ """for i in range(len(messages) - 1, -1, -1):if isinstance(messages[i], AIMessage):- last_ai_index = ilast_ai_message = cast("AIMessage", messages[i])- break+ tool_messages = [m for m in messages[i + 1 :] if isinstance(m, ToolMessage)]+ return last_ai_message, tool_messages- tool_messages = [m for m in messages[last_ai_index + 1 :] if isinstance(m, ToolMessage)]- return last_ai_message, tool_messages+ return None, []def _make_model_to_tools_edge(@@ -1588,9 +1593,14 @@ def _make_model_to_tools_edge()last_ai_message, tool_messages = _fetch_last_ai_and_tool_messages(state["messages"])++ # 2. if no AIMessage exists (e.g., messages were cleared), exit the loop+ if last_ai_message is None:+ return end_destination+tool_message_ids = [m.tool_call_id for m in tool_messages]- # 2. If the model hasn't called any tools, exit the loop+ # 3. If the model hasn't called any tools, exit the loop# this is the classic exit condition for an agent loopif len(last_ai_message.tool_calls) == 0:return end_destination@@ -1601,7 +1611,7 @@ def _make_model_to_tools_edge(if c["id"] not in tool_message_ids and c["name"] not in structured_output_tools]- # 3. If there are pending tool calls, jump to the tool node+ # 4. If there are pending tool calls, jump to the tool nodeif pending_tool_calls:return [Send(@@ -1615,11 +1625,11 @@ def _make_model_to_tools_edge(for tool_call in pending_tool_calls]- # 4. If there is a structured response, exit the loop+ # 5. If there is a structured response, exit the loopif "structured_response" in state:return end_destination- # 5. AIMessage has tool calls, but there are no pending tool calls which suggests+ # 6. AIMessage has tool calls, but there are no pending tool calls which suggests# the injection of artificial tool messages. Jump to the model nodereturn model_destination@@ -1663,7 +1673,11 @@ def _make_tools_to_model_edge(def tools_to_model(state: dict[str, Any]) -> str | None:last_ai_message, tool_messages = _fetch_last_ai_and_tool_messages(state["messages"])- # 1. Exit condition: All executed tools have return_direct=True+ # 1. If no AIMessage exists (e.g., messages were cleared), route to model+ if last_ai_message is None:+ return model_destination++ # 2. Exit condition: All executed tools have return_direct=True# Filter to only client-side tools (provider tools are not in tool_node)client_side_tool_calls = [c for c in last_ai_message.tool_calls if c["name"] in tool_node.tools_by_name@@ -1673,11 +1687,11 @@ def _make_tools_to_model_edge():return end_destination- # 2. Exit condition: A structured output tool was executed+ # 3. Exit condition: A structured output tool was executedif any(t.name in structured_output_tools for t in tool_messages):return end_destination- # 3. Default: Continue the loop+ # 4. Default: Continue the loop# Tool execution completed successfully, route back to the model# so it can process the tool results and decide the next action.return model_destinationdiff --git a/libs/langchain_v1/tests/unit_tests/agents/test_fetch_last_ai_and_tool_messages.py b/libs/langchain_v1/tests/unit_tests/agents/test_fetch_last_ai_and_tool_messages.pynew file mode 100644index 0000000000..bec7adaa93--- /dev/null+++ b/libs/langchain_v1/tests/unit_tests/agents/test_fetch_last_ai_and_tool_messages.py@@ -0,0 +1,107 @@+"""Unit tests for _fetch_last_ai_and_tool_messages helper function.++These tests verify that the helper function correctly handles edge cases,+including the scenario where no AIMessage exists in the message list+(fixes issue #34792).+"""++from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage++from langchain.agents.factory import _fetch_last_ai_and_tool_messages+++def test_fetch_last_ai_and_tool_messages_normal() -> None:+ """Test normal case with AIMessage and subsequent ToolMessages."""+ messages = [+ HumanMessage(content="Hello"),+ AIMessage(content="Hi there!", tool_calls=[{"name": "test", "id": "1", "args": {}}]),+ ToolMessage(content="Tool result", tool_call_id="1"),+ ]++ ai_msg, tool_msgs = _fetch_last_ai_and_tool_messages(messages)++ assert ai_msg is not None+ assert isinstance(ai_msg, AIMessage)+ assert ai_msg.content == "Hi there!"+ assert len(tool_msgs) == 1+ assert tool_msgs[0].content == "Tool result"+++def test_fetch_last_ai_and_tool_messages_multiple_ai() -> None:+ """Test that the last AIMessage is returned when multiple exist."""+ messages = [+ HumanMessage(content="First question"),+ AIMessage(content="First answer", id="ai1"),+ HumanMessage(content="Second question"),+ AIMessage(content="Second answer", id="ai2"),+ ]++ ai_msg, tool_msgs = _fetch_last_ai_and_tool_messages(messages)++ assert ai_msg is not None+ assert isinstance(ai_msg, AIMessage)+ assert ai_msg.content == "Second answer"+ assert ai_msg.id == "ai2"+ assert len(tool_msgs) == 0+++def test_fetch_last_ai_and_tool_messages_no_ai_message() -> None:+ """Test handling when no AIMessage exists in messages.++ This is the edge case that caused issue #34792 - UnboundLocalError+ when using RemoveMessage(id=REMOVE_ALL_MESSAGES) to clear thread messages.+ The function now returns None for the AIMessage, allowing callers to+ handle this edge case explicitly.+ """+ messages = [+ HumanMessage(content="Hello"),+ SystemMessage(content="You are a helpful assistant"),+ ]++ ai_msg, tool_msgs = _fetch_last_ai_and_tool_messages(messages)++ # Should return None when no AIMessage is found+ assert ai_msg is None+ assert len(tool_msgs) == 0+++def test_fetch_last_ai_and_tool_messages_empty_list() -> None:+ """Test handling of empty messages list.++ This can occur after RemoveMessage(id=REMOVE_ALL_MESSAGES) clears all messages.+ """+ messages: list = []++ ai_msg, tool_msgs = _fetch_last_ai_and_tool_messages(messages)++ # Should return None when no AIMessage is found+ assert ai_msg is None+ assert len(tool_msgs) == 0+++def test_fetch_last_ai_and_tool_messages_only_human_messages() -> None:+ """Test handling when only HumanMessages exist."""+ messages = [+ HumanMessage(content="Hello"),+ HumanMessage(content="Are you there?"),+ ]++ ai_msg, tool_msgs = _fetch_last_ai_and_tool_messages(messages)++ assert ai_msg is None+ assert len(tool_msgs) == 0+++def test_fetch_last_ai_and_tool_messages_ai_without_tool_calls() -> None:+ """Test AIMessage without tool_calls returns empty tool messages list."""+ messages = [+ HumanMessage(content="Hello"),+ AIMessage(content="Hi! How can I help you today?"),+ ]++ ai_msg, tool_msgs = _fetch_last_ai_and_tool_messages(messages)++ assert ai_msg is not None+ assert isinstance(ai_msg, AIMessage)+ assert ai_msg.content == "Hi! How can I help you today?"+ assert len(tool_msgs) == 0