messages_trimmer
llmfy.flow_engine.helper.messages_trimmer.messages_trimmer
logger = LLMfyLogger('LLMfy').get_logger()
module-attribute
count_tokens_approximately(messages)
Approximate token counter for messages. Rough estimate: 1 token ≈ 4 characters for English text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
List[Message]
|
List of Message objectscsada |
required |
Returns:
| Type | Description |
|---|---|
int
|
Approximate token count |
Source code in llmfy/flow_engine/helper/messages_trimmer/messages_trimmer.py
get_message_role(msg)
Extract role from Message object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
Message
|
Message object |
required |
Returns:
| Type | Description |
|---|---|
str
|
Role string (user, assistant, tool, system, etc.) |
Source code in llmfy/flow_engine/helper/messages_trimmer/messages_trimmer.py
trim_messages(messages, strategy='last', token_counter=None, max_tokens=None, start_on=None, end_on=None, include_system=True)
Trim messages based on token count and role constraints, similar to LangGraph's trim_messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
List[Message]
|
List of Message objects to trim |
required |
strategy
|
Literal['first', 'last']
|
"first" to keep earliest messages, "last" to keep latest messages |
'last'
|
token_counter
|
Optional[Callable[[List[Message]], int]]
|
Function to count tokens in messages. If None, uses count_tokens_approximately |
None
|
max_tokens
|
Optional[int]
|
Maximum number of tokens to keep. If None, no token limit is applied |
None
|
start_on
|
Optional[Union[str, Tuple[str, ...]]]
|
Role(s) that the trimmed messages must start with. Can be a string or tuple of strings |
None
|
end_on
|
Optional[Union[str, Tuple[str, ...]]]
|
Role(s) that the trimmed messages must end with. Can be a string or tuple of strings |
None
|
include_system
|
bool
|
Whether to always include system messages regardless of token limit |
True
|
Returns:
| Type | Description |
|---|---|
List[Message]
|
Trimmed list of Message objects |
Examples:
>>> messages = [Message(...), Message(...)]
>>> trimmed = trim_messages(
... messages,
... strategy="last",
... max_tokens=128,
... start_on="user",
... end_on=("user", "tool")
... )
Source code in llmfy/flow_engine/helper/messages_trimmer/messages_trimmer.py
safe_trim_messages(messages, max_tokens=1000)
Trim messages but ALWAYS preserve active tool context
Source code in llmfy/flow_engine/helper/messages_trimmer/messages_trimmer.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
tool_trim_messages(messages)
Trim messages but ALWAYS preserve active tool context.
Mechanism
Step 1 - Forward scan: Iterates all messages to collect: - tool_call_ids : all tool calls made by the assistant - resolved_tool_ids : tool calls that already have a TOOL result - last_tool_call_idx : index of the last assistant message with tool calls - last_message_is_tool_result : whether the last message is a TOOL result
Step 2 - Detect pending tools: pending_tool_ids = tool_call_ids - resolved_tool_ids Any tool call without a matching result is "pending."
Step 3 - Two paths: - Active tool cycle (pending tools OR last msg is tool result): Split at last_tool_call_idx, protect everything from there onward, trim earlier messages down to the last non-TOOL anchor to avoid starting with an orphaned TOOL result. - No active tool cycle: Aggressively trim — keep only messages[-1:].
Example
-- Example 1: messages = [ 0: USER "search for X" 1: ASSIST [tool_call: search, id="tc1"] 2: TOOL [tool_call_id="tc1", result="..."] 3: ASSIST "Based on results..." [tool_call: lookup, id="tc2"] <- last_tool_call_idx 4: TOOL [tool_call_id="tc2", result="..."] <- last_message_is_tool_result=True ]
tool_call_ids = {tc1, tc2} resolved_tool_ids = {tc1, tc2} pending_tool_ids = {} (empty, but last_message_is_tool_result=True -> protect context)
protected = messages[3:] -> [ASSIST tc2, TOOL tc2] trimmable = messages[:3] -> [USER, ASSIST tc1, TOOL tc1] anchor = index 1 (last non-TOOL in trimmable) -> ASSIST tc1
result = [ASSIST tc1, TOOL tc1] + [ASSIST tc2, TOOL tc2]
USER "search for X" is dropped; active tool context is fully preserved.
-- Example 2 (parallel tool calls in a single ASSIST message): messages = [ 0: USER "search for X" 1: ASSIST [tool_call: search, id="tc1", tool_call: search, id="tc2"] <- last_tool_call_idx 2: TOOL [tool_call_id="tc1", result="..."] 3: TOOL [tool_call_id="tc2", result="..."] <- last_message_is_tool_result=True ]
tool_call_ids = {tc1, tc2} resolved_tool_ids = {tc1, tc2} pending_tool_ids = {} (empty, but last_message_is_tool_result=True -> protect context)
Condition: (False) or True -> True -> enters protect-context path
protected = messages[1:] -> [ASSIST(tc1,tc2), TOOL(tc1), TOOL(tc2)] trimmable = messages[:1] -> [USER] anchor = index 0 (USER is not TOOL, no skip needed)
result = [USER] + [ASSIST(tc1,tc2), TOOL(tc1), TOOL(tc2)]
All 4 messages preserved; parallel tool results stay intact.
Source code in llmfy/flow_engine/helper/messages_trimmer/messages_trimmer.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |