Chat template: bound the tool block scan

#10
by vMaroon - opened

At the first tool message of a block, the template collects the block with a loop that runs to the end of the conversation. With one tool call per turn that is one full scan per turn, so render time grows with the square of the history and a long agent session passes vLLM's 30 s render timeout.

This counts the length of each tool block in one pass before the message loop, and the collecting loop stops at the end of its block. The rendered block is unchanged.

Tool calls main this PR
400 0.39 s 0.02 s
1,600 5.9 s 0.09 s
3,200 24 s 0.19 s

transformers 5.22.1 with jinja2 3.1.6, one M4 core, one tool call per assistant message.

Output is byte-identical to main on 46,000 randomized conversations (duplicate, unmatched and case-variant ids, shuffled and missing results), under jinja2 and under MiniJinja 3.1.0 through its Python binding.

The reordering of results inside one block compares every result with every tool call of the turn, about 6 s at 3,200 parallel calls. I left it for a separate change.

Ready to merge
This branch is ready to get merged automatically.

Sign up or log in to comment