@@ -65,3 +65,46 @@ def _remove_tool_types_from_input(
65
65
continue
66
66
filtered_items .append (item )
67
67
return tuple (filtered_items )
68
+
69
+
70
+ def keep_last_n_items (
71
+ handoff_input_data : HandoffInputData ,
72
+ n : int ,
73
+ keep_tool_messages : bool = True
74
+ ) -> HandoffInputData :
75
+ """
76
+ Keep only the last n items in the input history.
77
+ If keep_tool_messages is False, remove tool messages first.
78
+
79
+ Args:
80
+ handoff_input_data: The input data to filter
81
+ n: Number of items to keep from the end. Must be a positive integer.
82
+ If n is 1, only the last item is kept.
83
+ If n is greater than the number of items, all items are kept.
84
+ If n is less than or equal to 0, it raises a ValueError.
85
+ keep_tool_messages: If False, removes tool messages before filtering
86
+
87
+ Raises:
88
+ ValueError: If n is not a positive integer
89
+ """
90
+ if not isinstance (n , int ):
91
+ raise ValueError (f"n must be an integer, got { type (n ).__name__ } " )
92
+ if n <= 0 :
93
+ raise ValueError (f"n must be a positive integer, got { n } " )
94
+
95
+ data = handoff_input_data
96
+ if not keep_tool_messages :
97
+ data = remove_all_tools (data )
98
+
99
+ # Always ensure input_history and new_items are tuples for consistent slicing and return
100
+ history = (
101
+ tuple (data .input_history )[- n :]
102
+ if isinstance (data .input_history , tuple )
103
+ else data .input_history
104
+ )
105
+
106
+ return HandoffInputData (
107
+ input_history = history ,
108
+ pre_handoff_items = tuple (data .pre_handoff_items ),
109
+ new_items = tuple (data .new_items ),
110
+ )
0 commit comments