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
9- from .constants import MAX_CONSECUTIVE_THINKING_MESSAGES
10+ from ..exceptions import AgentTerminationException
11+ from .constants import (
12+ DEFAULT_MAX_CONSECUTIVE_THINKING_MESSAGES ,
13+ DEFAULT_MAX_LLM_MESSAGES ,
14+ )
1015from .types import FLOW_CONTROL_TOOLS , AgentGraphState
1116from .utils import count_consecutive_thinking_messages
1217
@@ -46,8 +51,9 @@ def _filter_control_flow_tool_calls(
4651def create_llm_node (
4752 model : BaseChatModel ,
4853 tools : Sequence [BaseTool ] | None = None ,
49- thinking_messages_limit : int = MAX_CONSECUTIVE_THINKING_MESSAGES ,
5054 is_conversational : bool = False ,
55+ llm_messages_limit : int = DEFAULT_MAX_LLM_MESSAGES ,
56+ thinking_messages_limit : int = DEFAULT_MAX_CONSECUTIVE_THINKING_MESSAGES ,
5157):
5258 """Create LLM node with dynamic tool_choice enforcement.
5359
@@ -57,6 +63,8 @@ def create_llm_node(
5763 Args:
5864 model: The chat model to use
5965 tools: Available tools to bind
66+ is_conversational: Whether this is a conversational agent
67+ llm_messages_limit: Maximum number of LLM calls allowed per execution
6068 thinking_messages_limit: Max consecutive LLM responses without tool calls
6169 before enforcing tool usage. 0 = force tools every time.
6270 """
@@ -67,6 +75,15 @@ def create_llm_node(
6775 async def llm_node (state : AgentGraphState ):
6876 messages : list [AnyMessage ] = state .messages
6977
78+ agent_ai_messages = sum (1 for msg in messages if isinstance (msg , AIMessage ))
79+ if agent_ai_messages >= llm_messages_limit :
80+ raise AgentTerminationException (
81+ code = UiPathErrorCode .EXECUTION_ERROR ,
82+ title = f"Maximum iterations of '{ llm_messages_limit } ' reached." ,
83+ detail = "Verify the agent's trajectory or consider increasing the max iterations in the agent's settings." ,
84+ category = UiPathErrorCategory .USER ,
85+ )
86+
7087 consecutive_thinking_messages = count_consecutive_thinking_messages (messages )
7188
7289 if (
0 commit comments