Chat template: look up tool names in one pass

#27
by vMaroon - opened
Files changed (1) hide show
  1. chat_template.jinja +39 -1
chat_template.jinja CHANGED
@@ -103,6 +103,41 @@
103
  {{- "<|end|>" }}
104
  {%- endif -%}
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  {#- ======== Render main messages ======== #}
107
  {%- for message in messages -%}
108
  {%- if message.role == 'user' -%}
@@ -114,7 +149,10 @@
114
  {{- "<|begin|>tool<|tool_response|>" }}
115
  {%- endif -%}
116
  {{- "<|tool_response:begin|>" + message.tool_call_id + "<|tool_response:name|>" }}
117
- {{- get_tool_name(messages, message.tool_call_id) }}
 
 
 
118
  {{- "<|tool_response:result|>" }}
119
  {{- message.content }}
120
  {{- "<|tool_response:end|>" }}
 
103
  {{- "<|end|>" }}
104
  {%- endif -%}
105
 
106
+ {#- tool_hits: one entry per tool message with a string tool_call_id, in message order: the assistant tool calls
107
+ with that id. Tool calls and tool messages are tagged, sorted by id together (stable, so the calls of an id come
108
+ first and keep their order) and paired in one pass. -#}
109
+ {%- set tl = namespace(items=[], n=0) -%}
110
+ {%- for m in messages -%}
111
+ {%- if m.role == 'assistant' and m.tool_calls -%}
112
+ {%- for tc in m.tool_calls -%}
113
+ {%- if tc.id is string -%}
114
+ {%- set tl.items = tl.items + [{'id': tc.id, 'k': -1, 'tc': tc}] -%}
115
+ {%- endif -%}
116
+ {%- endfor -%}
117
+ {%- endif -%}
118
+ {%- endfor -%}
119
+ {%- for m in messages -%}
120
+ {%- if m.role == 'tool' and m.tool_call_id is string -%}
121
+ {%- set tl.items = tl.items + [{'id': m.tool_call_id, 'k': tl.n}] -%}
122
+ {%- set tl.n = tl.n + 1 -%}
123
+ {%- endif -%}
124
+ {%- endfor -%}
125
+ {%- set pr = namespace(id=none, tcs=[], hits=[]) -%}
126
+ {%- for it in tl.items | sort(attribute='id', case_sensitive=true) -%}
127
+ {%- if it.k < 0 -%}
128
+ {%- if pr.id is not none and pr.id == it.id -%}
129
+ {%- set pr.tcs = pr.tcs + [it.tc] -%}
130
+ {%- else -%}
131
+ {%- set pr.id = it.id -%}
132
+ {%- set pr.tcs = [it.tc] -%}
133
+ {%- endif -%}
134
+ {%- else -%}
135
+ {%- set pr.hits = pr.hits + [{'k': it.k, 'tcs': pr.tcs if pr.id is not none and pr.id == it.id else []}] -%}
136
+ {%- endif -%}
137
+ {%- endfor -%}
138
+ {%- set tool_hits = pr.hits | sort(attribute='k') -%}
139
+ {%- set tl.n = 0 -%}
140
+
141
  {#- ======== Render main messages ======== #}
142
  {%- for message in messages -%}
143
  {%- if message.role == 'user' -%}
 
149
  {{- "<|begin|>tool<|tool_response|>" }}
150
  {%- endif -%}
151
  {{- "<|tool_response:begin|>" + message.tool_call_id + "<|tool_response:name|>" }}
152
+ {%- for tc in tool_hits[tl.n].tcs -%}
153
+ {{- tc.function.name }}
154
+ {%- endfor -%}
155
+ {%- set tl.n = tl.n + 1 -%}
156
  {{- "<|tool_response:result|>" }}
157
  {{- message.content }}
158
  {{- "<|tool_response:end|>" }}