Chat template: map tool results to tool call positions in one pass

#18
by vMaroon - opened

With regen_tool_call_ids (the default), tool_call_id_to_int loops over every tool call in the conversation for each tool result. Render time grows with the square of the tool calls in the history, so a long agent session passes vLLM's 30 s render timeout.

This builds the mapping once before the message loop: tool calls and tool messages are sorted together by id and paired in one pass, and format_tool_message gets the position as an argument. First match wins and an unmatched id renders empty, as on main. A tool_call_id that is not a string keeps the loop. It only uses sort, namespace and list concatenation, so it renders under MiniJinja too.

Tool calls main this PR
400 0.69 s 0.03 s
1,600 11.0 s 0.14 s
3,200 44 s 0.34 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 54,000 randomized conversations (duplicate, unmatched, case-variant and non-string ids, results before their call, regen_tool_call_ids off, documents set), under jinja2 and under MiniJinja 3.1.0 through its Python binding.

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

Sign up or log in to comment