55from langchain_core .language_models import BaseChatModel
66from langchain_core .messages import AIMessage , AnyMessage , ToolCall
77from langchain_core .tools import BaseTool
8+ from uipath .runtime .errors import UiPathErrorCategory , UiPathErrorCode
89
10+ from ..exceptions import AgentTerminationException
11+ from .constants import (
12+ DEFAULT_MAX_CONSECUTIVE_THINKING_MESSAGES ,
13+ DEFAULT_MAX_LLM_MESSAGES ,
14+ )
915from .constants import MAX_CONSECUTIVE_THINKING_MESSAGES
1016from .types import FLOW_CONTROL_TOOLS , AgentGraphState
1117from .utils import count_consecutive_thinking_messages
@@ -46,8 +52,9 @@ def _filter_control_flow_tool_calls(
4652def create_llm_node (
4753 model : BaseChatModel ,
4854 tools : Sequence [BaseTool ] | None = None ,
49- thinking_messages_limit : int = MAX_CONSECUTIVE_THINKING_MESSAGES ,
5055 is_conversational : bool = False ,
56+ llm_messages_limit : int = DEFAULT_MAX_LLM_MESSAGES ,
57+ thinking_messages_limit : int = DEFAULT_MAX_CONSECUTIVE_THINKING_MESSAGES ,
5158):
5259 """Create LLM node with dynamic tool_choice enforcement.
5360
@@ -57,6 +64,8 @@ def create_llm_node(
5764 Args:
5865 model: The chat model to use
5966 tools: Available tools to bind
67+ is_conversational: Whether this is a conversational agent
68+ llm_messages_limit: Maximum number of LLM calls allowed per execution
6069 thinking_messages_limit: Max consecutive LLM responses without tool calls
6170 before enforcing tool usage. 0 = force tools every time.
6271 """
@@ -67,6 +76,15 @@ def create_llm_node(
6776 async def llm_node (state : AgentGraphState ):
6877 messages : list [AnyMessage ] = state .messages
6978
79+ agent_ai_messages = sum (1 for msg in messages if isinstance (msg , AIMessage ))
80+ if agent_ai_messages >= llm_messages_limit :
81+ raise AgentTerminationException (
82+ code = UiPathErrorCode .EXECUTION_ERROR ,
83+ title = f"Maximum iterations of '{ llm_messages_limit } ' reached." ,
84+ detail = "Verify the agent's trajectory or consider increasing the max iterations in the agent's settings." ,
85+ category = UiPathErrorCategory .USER ,
86+ )
87+
7088 consecutive_thinking_messages = count_consecutive_thinking_messages (messages )
7189
7290 if (
0 commit comments