55from langchain_core .language_models import BaseChatModel
66from langchain_core .messages import AIMessage , AnyMessage
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 AgentGraphState
1116from .utils import count_consecutive_thinking_messages
1217
@@ -36,8 +41,9 @@ def _get_required_tool_choice_by_model(
3641def create_llm_node (
3742 model : BaseChatModel ,
3843 tools : Sequence [BaseTool ] | None = None ,
39- thinking_messages_limit : int = MAX_CONSECUTIVE_THINKING_MESSAGES ,
4044 is_conversational : bool = False ,
45+ llm_messages_limit : int = DEFAULT_MAX_LLM_MESSAGES ,
46+ thinking_messages_limit : int = DEFAULT_MAX_CONSECUTIVE_THINKING_MESSAGES ,
4147):
4248 """Create LLM node with dynamic tool_choice enforcement.
4349
@@ -47,6 +53,8 @@ def create_llm_node(
4753 Args:
4854 model: The chat model to use
4955 tools: Available tools to bind
56+ is_conversational: Whether this is a conversational agent
57+ llm_messages_limit: Maximum number of LLM calls allowed per execution
5058 thinking_messages_limit: Max consecutive LLM responses without tool calls
5159 before enforcing tool usage. 0 = force tools every time.
5260 """
@@ -57,6 +65,15 @@ def create_llm_node(
5765 async def llm_node (state : AgentGraphState ):
5866 messages : list [AnyMessage ] = state .messages
5967
68+ agent_ai_messages = sum (1 for msg in messages if isinstance (msg , AIMessage ))
69+ if agent_ai_messages >= llm_messages_limit :
70+ raise AgentTerminationException (
71+ code = UiPathErrorCode .EXECUTION_ERROR ,
72+ title = f"Maximum iterations of '{ llm_messages_limit } ' reached." ,
73+ detail = "Verify the agent's trajectory or consider increasing the max iterations in the agent's settings." ,
74+ category = UiPathErrorCategory .USER ,
75+ )
76+
6077 consecutive_thinking_messages = count_consecutive_thinking_messages (messages )
6178
6279 if (
0 commit comments