@@ -41,6 +41,8 @@ class ChatWithNextcloud(BaseChatModel):
4141 Union [typing .Dict [str , Any ], type , Callable , BaseTool ]] = []
4242 TIMEOUT : int = 60 * 30 # 30 minutes
4343 MAX_MESSAGE_HISTORY : int = 42
44+ TOOL_OUTPUT_TRUNCATE_AFTER : int = 10
45+ TOOL_OUTPUT_MAX_LENGTH : int = 2000
4446 POLL_WAIT_TIME : int = 5
4547 STREAMING_POLL_WAIT_TIME : int = 1
4648
@@ -54,8 +56,19 @@ def _build_task_input(self, messages: list[BaseMessage]) -> dict[str, typing.Any
5456 task_input ['system_prompt' ] = messages [0 ].content
5557 messages = messages [1 :]
5658
57- # Impose a history limit to avoid the token intake exploding
58- messages = messages [- self .MAX_MESSAGE_HISTORY :]
59+ # Impose a history limit on non-tool messages to avoid token intake exploding.
60+ # Tool messages don't count toward the limit so tool_call/tool_result pairs
61+ # stay intact even in tool-heavy conversations.
62+ non_tool_count = 0
63+ cutoff_idx = 0
64+ # idx=0 is the first message, idx=len-1 is the most recent, so we walk backward
65+ for i in range (len (messages ) - 1 , - 1 , - 1 ):
66+ if messages [i ].type != 'tool' :
67+ non_tool_count += 1
68+ if non_tool_count > self .MAX_MESSAGE_HISTORY :
69+ cutoff_idx = i + 1
70+ break
71+ messages = messages [cutoff_idx :]
5972
6073 # first message cannot be a tool message
6174 while len (messages ) > 0 and messages [0 ].type == 'tool' :
@@ -78,10 +91,14 @@ def _build_task_input(self, messages: list[BaseMessage]) -> dict[str, typing.Any
7891 else :
7992 task_input ['input' ] = message .content
8093 elif message .type == 'tool' :
94+ content = message .content
95+ age = len (messages ) - 1 - i
96+ if age > self .TOOL_OUTPUT_TRUNCATE_AFTER and isinstance (content , str ) and len (content ) > self .TOOL_OUTPUT_MAX_LENGTH :
97+ content = content [:self .TOOL_OUTPUT_MAX_LENGTH ] + "…[truncated]"
8198 if len (messages )- 1 != i :
82- history .append (json .dumps ({"role" : "tool" , "content" : message . content , "name" : message .name , "tool_call_id" : message .tool_call_id }))
99+ history .append (json .dumps ({"role" : "tool" , "content" : content , "name" : message .name , "tool_call_id" : message .tool_call_id }))
83100 else :
84- task_input ['tool_message' ].append ({"name" : message .name , "content" : message . content , "tool_call_id" : message .tool_call_id })
101+ task_input ['tool_message' ].append ({"name" : message .name , "content" : content , "tool_call_id" : message .tool_call_id })
85102 else :
86103 print (message )
87104 raise Exception ("Message type not found" )
0 commit comments