11import json
2+
23from langchain_core .messages import ToolMessage
4+
35from .config import Config
46
57INDIVIDUAL_MIN_LENGTH = 100
68
9+
710def collect_long_strings (obj ):
811 field_info = []
12+
913 def _collect (obj ):
1014 if isinstance (obj , dict ):
1115 for key , value in obj .items ():
1216 if isinstance (value , str ) and len (value ) > INDIVIDUAL_MIN_LENGTH :
13- field_info .append ({
14- 'length' : len (value ),
15- 'dict' : obj ,
16- 'key' : key ,
17- })
17+ field_info .append (
18+ {
19+ "length" : len (value ),
20+ "dict" : obj ,
21+ "key" : key ,
22+ }
23+ )
1824 elif isinstance (value , (dict , list )):
1925 _collect (value )
2026 elif isinstance (obj , list ):
2127 for item in obj :
2228 if isinstance (item , (dict , list )):
2329 _collect (item )
24-
30+
2531 _collect (obj )
2632 return field_info
2733
2834
2935def truncate_by_length (content , max_length ):
3036 """
31- Truncate JSON content by recursively truncating the longest fields until content is under limit.
37+ Truncate JSON content by recursively truncating the longest fields until content is under limit.
3238 Preserves structure and smaller fields with minimum loss of information.
3339 """
3440 try :
3541 data = json .loads (content )
36- field_info = sorted (collect_long_strings (data ), key = lambda x : x [' length' ])
42+ field_info = sorted (collect_long_strings (data ), key = lambda x : x [" length" ])
3743
3844 cur_length = len (json .dumps (data ))
39- while field_info and cur_length - max_length > 0 :
45+ while field_info and cur_length - max_length > 0 :
4046 longest = field_info .pop ()
4147 excess = cur_length - max_length
42- new_length = max (INDIVIDUAL_MIN_LENGTH , longest [' length' ] - excess )
43- cur_length -= longest [' length' ] - new_length
44- longest [' dict' ][longest [' key' ]] = (
45- longest [' dict' ][longest [' key' ]][:new_length ] +
46- f"... [TRUNCATED: { longest ['length' ] - new_length } chars removed]"
48+ new_length = max (INDIVIDUAL_MIN_LENGTH , longest [" length" ] - excess )
49+ cur_length -= longest [" length" ] - new_length
50+ longest [" dict" ][longest [" key" ]] = (
51+ longest [" dict" ][longest [" key" ]][:new_length ]
52+ + f"... [TRUNCATED: { longest ['length' ] - new_length } chars removed]"
4753 )
48-
54+
4955 if cur_length <= max_length :
5056 return json .dumps (data )
5157 except (json .JSONDecodeError , Exception ):
@@ -61,13 +67,20 @@ def truncate_tool_messages(state):
6167 """
6268 messages = state .get ("messages" , [])
6369 modified_messages = []
64-
65- for i ,msg in enumerate (messages ):
66- if isinstance (msg , ToolMessage ) and len (msg .content ) > Config .MAX_CONTENT_LENGTH :
67- truncated_msg = msg .model_copy (update = {
68- 'content' : truncate_by_length (msg .content , Config .MAX_CONTENT_LENGTH )
69- })
70+
71+ for i , msg in enumerate (messages ):
72+ if (
73+ isinstance (msg , ToolMessage )
74+ and len (msg .content ) > Config .MAX_CONTENT_LENGTH
75+ ):
76+ truncated_msg = msg .model_copy (
77+ update = {
78+ "content" : truncate_by_length (
79+ msg .content , Config .MAX_CONTENT_LENGTH
80+ )
81+ }
82+ )
7083 modified_messages .append (truncated_msg )
7184 else :
7285 modified_messages .append (msg )
73- return {"messages" : modified_messages }
86+ return {"messages" : modified_messages }
0 commit comments