cppowboy commited on
Commit
e8a65f6
1 Parent(s): bfe2f6c

remove minicpm tokenizer (#29)

Browse files

- remove minicpm tokenizer (536445ffcc9e4c7e4bf21ccc6e0118baae01671e)

Files changed (2) hide show
  1. tokenization_minicpm.py +0 -433
  2. tokenizer_config.json +1 -7
tokenization_minicpm.py DELETED
@@ -1,433 +0,0 @@
1
- import ast
2
- import json
3
- import keyword
4
- import traceback
5
- import uuid
6
- from collections import deque
7
- from logging import getLogger
8
- from typing import Any, Dict, List, Optional, Union
9
-
10
- from datamodel_code_generator import DataModelType
11
- from datamodel_code_generator.format import PythonVersion
12
- from datamodel_code_generator.model import get_data_model_types
13
- from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
14
- from jsonschema import Draft202012Validator, exceptions, validate
15
-
16
- from transformers import LlamaTokenizerFast
17
- from transformers.tokenization_utils_base import BatchEncoding
18
- from transformers.utils import TensorType
19
- from copy import deepcopy
20
-
21
-
22
- logger = getLogger(__name__)
23
-
24
-
25
- class MiniCPMTokenizer(LlamaTokenizerFast):
26
- def apply_chat_template(
27
- self,
28
- conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]]],
29
- tools: Optional[List[Dict]] = None,
30
- documents: Optional[List[Dict[str, str]]] = None,
31
- chat_template: Optional[str] = None,
32
- add_generation_prompt: bool = False,
33
- tokenize: bool = True,
34
- padding: bool = False,
35
- truncation: bool = False,
36
- max_length: Optional[int] = None,
37
- return_tensors: Optional[Union[str, TensorType]] = None,
38
- return_dict: bool = False,
39
- return_assistant_tokens_mask: bool = False,
40
- tokenizer_kwargs: Optional[Dict[str, Any]] = None,
41
- **kwargs,
42
- ) -> Union[str, List[int], List[str], List[List[int]], BatchEncoding]:
43
- if tools is None:
44
- tools = []
45
- check_messages(conversation, tools)
46
- functions = [tool["function"] for tool in tools]
47
- conversation = self.reorder_tool_response(conversation)
48
- input_messages = input_format(conversation, functions, add_to_system=True)
49
- return super().apply_chat_template(
50
- input_messages,
51
- tools=None,
52
- documents=documents,
53
- chat_template=chat_template,
54
- add_generation_prompt=add_generation_prompt,
55
- tokenize=tokenize,
56
- padding=padding,
57
- truncation=truncation,
58
- max_length=max_length,
59
- return_tensors=return_tensors,
60
- return_dict=return_dict,
61
- return_assistant_tokens_mask=return_assistant_tokens_mask,
62
- tokenizer_kwargs=tokenizer_kwargs,
63
- **kwargs,
64
- )
65
-
66
- def reorder_tool_response(self, conversation: List[Dict[str, str]]):
67
- tool_call_ids = deque()
68
- tool_responses = deque()
69
-
70
- new_conversation = []
71
- for message in conversation:
72
- if (
73
- message["role"] == "assistant"
74
- and "tool_calls" in message
75
- and message["tool_calls"] is not None
76
- and len(message["tool_calls"]) > 0
77
- ):
78
- for tool_call in message["tool_calls"]:
79
- tool_call_ids.append(tool_call["id"])
80
- new_conversation.append(message)
81
- elif message["role"] == "tool":
82
- tool_call_id = message.get("tool_call_id", None)
83
- if tool_call_id == tool_call_ids[0]:
84
- new_conversation.append(message)
85
- tool_call_ids.popleft()
86
- while (
87
- len(tool_call_ids) > 0
88
- and len(tool_responses) > 0
89
- and tool_call_ids[0] == tool_responses[0]["tool_call_id"]
90
- ):
91
- new_conversation.append(tool_responses.popleft())
92
- tool_call_ids.popleft()
93
- else:
94
- tool_responses.append(message)
95
- else:
96
- new_conversation.append(message)
97
- if len(tool_call_ids) != 0:
98
- raise ValueError(f"Message error, not all tool calls have responses: {tool_call_ids}")
99
- if len(tool_responses) != 0:
100
- raise ValueError(f"Message error, too many tool responses: {tool_responses}")
101
- return new_conversation
102
-
103
- def decode_function_call(
104
- self,
105
- sequence: str,
106
- tool_call_start="<|tool_call_start|>",
107
- tool_call_end="<|tool_call_end|>",
108
- thought_start="<|thought_start|>",
109
- thought_end="<|thought_end|>",
110
- ):
111
- if thought_end in sequence and thought_start in sequence:
112
- thought_string, sequence = sequence.rsplit(thought_end, 1)
113
- thought_string = thought_string.split(thought_start, 1)[1]
114
- else:
115
- thought_string = ""
116
- if tool_call_start in sequence and tool_call_end in sequence:
117
- tool_call_string, content = sequence.rsplit(tool_call_end, 1)
118
- tool_call_string = tool_call_string.split(tool_call_start, 1)[1]
119
- try:
120
- tool_calls = []
121
- tool_call_string = tool_call_string.strip()
122
- if tool_call_string.startswith("```"):
123
- tool_call_string = tool_call_string.lstrip("```").strip()
124
- if tool_call_string.startswith("python"):
125
- tool_call_string = tool_call_string.lstrip("python").strip()
126
- if tool_call_string.endswith("```"):
127
- tool_call_string = tool_call_string.rstrip("```").strip()
128
- for kw in keyword.kwlist:
129
- tool_call_string = tool_call_string.replace("," + kw + "=", "," + kw + "_=")
130
- tool_call_string = tool_call_string.replace(" " + kw + "=", " " + kw + "_=")
131
- tool_call_string = tool_call_string.replace("(" + kw + "=", "(" + kw + "_=")
132
-
133
- parsed = ast.parse(tool_call_string)
134
-
135
- for elem in parsed.body:
136
- assert isinstance(elem.value, ast.Call)
137
- calls = resolve_ast_call(elem.value)
138
-
139
- for func_name, func_args in calls.items():
140
- new_args = {}
141
- for k, v in func_args.items():
142
- for kw in keyword.kwlist:
143
- if k == kw + "_":
144
- k = kw
145
- new_args[k] = v
146
-
147
- this_one = {"name": func_name, "arguments": new_args}
148
- tool_calls.append(this_one)
149
-
150
- return {
151
- "content": content,
152
- "tool_calls": [
153
- {"type": "function", "function": tool_call, "id": "call_" + uuid.uuid4().hex}
154
- for tool_call in tool_calls
155
- ],
156
- "role": "assistant",
157
- }
158
- except:
159
- logger.error(traceback.format_exc())
160
- return {
161
- "content": content,
162
- "role": "assistant",
163
- "thought": thought_string,
164
- }
165
- else:
166
- return {
167
- "content": sequence,
168
- "role": "assistant",
169
- "thought": thought_string,
170
- }
171
-
172
-
173
- def check_messages(conversation: List[Dict[str, str]], tools: List[Dict]):
174
- if tools is not None:
175
- for tool in tools:
176
- if "type" not in tool or tool["type"] != "function":
177
- raise ValueError(f"Tool {tool} is not valid")
178
- if "name" not in tool["function"]:
179
- raise ValueError(f"Tool {tool} is not valid")
180
- if "parameters" not in tool["function"] or not check_tool(tool["function"]["parameters"]["properties"]):
181
- raise ValueError(f"Tool {tool} is not valid")
182
- for message in conversation:
183
- if message["role"] == "assistant" and "tool_calls" in message and len(message["tool_calls"]) > 0:
184
- for tool_call in message["tool_calls"]:
185
- if "id" not in tool_call:
186
- raise ValueError(f"Tool call {tool_call} is not valid")
187
- if tool_call["type"] != "function":
188
- raise ValueError(f"Tool call {tool_call} is not valid")
189
- if "function" not in tool_call:
190
- raise ValueError(f"Tool call {tool_call} is not valid")
191
- if not check_tool(tool_call["function"]):
192
- raise ValueError(f"Tool call function {tool_call['function']} is not valid")
193
- elif message["role"] == "tool":
194
- if "tool_call_id" not in message:
195
- raise ValueError(f"Tool message {message['content']} is not valid")
196
-
197
-
198
- def check_tool(tool_schema):
199
- try:
200
- Draft202012Validator.check_schema(tool_schema)
201
- return True
202
- except exceptions.SchemaError as e:
203
- print(f"SchemaError: {e}")
204
- return False
205
-
206
-
207
- def check_args(args, tool_schema):
208
- try:
209
- validate(instance=args, schema=tool_schema)
210
- return True
211
- except exceptions.ValidationError as e:
212
- print(f"Data failed validation: {e}")
213
- return False
214
-
215
-
216
- def message_format(msg, system_suffix="", user_prefix=""):
217
- if "thought" in msg and msg["thought"] is not None and len(msg["thought"]) > 0:
218
- thought_prefix = f"<|thought_start|>\n{msg['thought']}\n<|thought_end|>\n"
219
- else:
220
- thought_prefix = ""
221
- if msg["role"] == "assistant":
222
- content = msg.get("content", "")
223
- if content is None:
224
- content = ""
225
- if "tool_calls" in msg and msg["tool_calls"] is not None and len(msg["tool_calls"]) > 0:
226
-
227
- def add_quotes(variable):
228
- if isinstance(variable, str):
229
- return repr(variable)
230
- else:
231
- return str(variable)
232
-
233
- tool_calls = []
234
- for _tool_call in msg["tool_calls"]:
235
- if _tool_call is None:
236
- continue
237
- tool_call = _tool_call["function"]
238
- tool_name = tool_call["name"]
239
- if "arguments" not in tool_call or tool_call["arguments"] is None:
240
- continue
241
- if isinstance(tool_call["arguments"], str):
242
- try:
243
- tool_call["arguments"] = json.loads(tool_call["arguments"])
244
- except:
245
- continue
246
- args = ",".join([k + "=" + add_quotes(v) for k, v in tool_call["arguments"].items()])
247
- tool_calls.append(f"{tool_name}({args})")
248
-
249
- content = (
250
- thought_prefix
251
- + "<|tool_call_start|>\n```python\n"
252
- + "\n".join(tool_calls).strip()
253
- + "\n```\n<|tool_call_end|>\n"
254
- + content
255
- )
256
- # msg["tool_call_string"] = "\n".join(tool_calls).strip()
257
- msg["content"] = content
258
- else:
259
- content = thought_prefix + content
260
- msg["content"] = content
261
- elif msg["role"] == "user":
262
- if user_prefix != "":
263
- msg["content"] = user_prefix + "\n" + msg["content"]
264
- elif msg["role"] == "system":
265
- msg["content"] = msg["content"] + "\n" + system_suffix
266
- msg["content"] = msg["content"]
267
- return msg
268
-
269
-
270
- def jsonschema_to_code(jsonschema: dict) -> str:
271
- input_text = json.dumps(jsonschema)
272
- data_model_types = get_data_model_types(
273
- DataModelType.PydanticBaseModel,
274
- PythonVersion.PY_310,
275
- )
276
- parser = JsonSchemaParser(
277
- source=input_text,
278
- data_model_type=data_model_types.data_model,
279
- data_model_root_type=data_model_types.root_model,
280
- data_model_field_type=data_model_types.field_model,
281
- data_type_manager_type=data_model_types.data_type_manager,
282
- target_python_version=PythonVersion.PY_310,
283
- dump_resolve_reference_action=data_model_types.dump_resolve_reference_action,
284
- field_constraints=True,
285
- )
286
- results = parser.parse()
287
- return results
288
-
289
-
290
- def transform_function(function: dict):
291
- """turn json format of function into signature"""
292
- params, default_params = [], []
293
- for prop_name, prop in function["parameters"]["properties"].items():
294
- if "default" in prop:
295
- default_params.append(f'{prop_name}={repr(prop["default"])}')
296
- elif prop_name not in function["parameters"].get("required", []):
297
- default_params.append(f"{prop_name}={repr(None)}")
298
- else:
299
- params.append(prop_name)
300
- ps = ", ".join(params + default_params)
301
- res = "def {f_name}({ps}):\n".format(f_name=function["name"], ps=ps)
302
- f_des = function.get("description", "")
303
- content = jsonschema_to_code(function["parameters"])
304
- if "class" in content:
305
- i = content.index("class")
306
- # print(content[:i])
307
- content = content[i:]
308
- classes, args = content.split("class Model(BaseModel):", 1)
309
- lint_msg = f' """\n {f_des}\n Args:\n{args}\n """\n'
310
- res += lint_msg
311
- if len(classes) > 0:
312
- res = classes + res
313
- return res
314
-
315
-
316
- def input_format(messages: List[Dict], tools: List[Dict], add_to_system=True):
317
- """
318
- Process the input messages, global_arguments, tools, tool_choice,
319
- and convert it into a input string.
320
- The global arguments and tools can not be both empty.
321
- parameters:
322
- messages: List[Dict]
323
- the input messages
324
- For example:
325
- tools: List[Dict]
326
- the tools list you can use
327
- For example:
328
- """
329
- messages = deepcopy(messages)
330
- tools = deepcopy(tools)
331
- if tools is not None and len(tools) > 0:
332
- header = (
333
- "from enum import Enum\nfrom typing import List, Dict, Optional\nfrom pydantic import BaseModel, Field\n\n"
334
- )
335
- tools_string = header
336
- for tool in tools:
337
- try:
338
- tools_string += "\n\n" + transform_function(tool)
339
- except:
340
- pass
341
- tools_template = """# Functions
342
- Here is a list of functions that you can invoke:
343
- ```python
344
- {tools}
345
- ```
346
-
347
- # Function Call Rule and Output Format
348
- - If the user's question can be answered without calling any function, please answer the user's question directly. In this situation, you should return your thought and answer the user's question directly.
349
- - If the user cannot be answered without calling any function, and the user does not provide enough information to call functions, please ask the user for more information. In this situation, you should return your thought and ask the user for more information.
350
- - If the user's question cannot be answered without calling any function, and the user has provided enough information to call functions to solve it, you should call the functions. In this situation, the assistant should return your thought and call the functions.
351
- - Use default parameters unless the user has specified otherwise.
352
- - You should answer in the following format:
353
-
354
- <|thought_start|>
355
- {{explain why the user's question can be answered without calling a function or why you should ask the user for more information or why you should call one or more functions and your plan to solve the user's question.}}
356
- <|thought_end|>
357
- <|tool_call_start|>
358
- ```python
359
- func1(params_name=params_value, params_name2=params_value2...)
360
- func2(params)
361
- ```
362
- <|tool_call_end|>
363
- {{answer the user's question directly or ask the user for more information}}
364
- """
365
- tools_string = tools_template.format(tools=tools_string)
366
- else:
367
- tools_string = ""
368
-
369
- if add_to_system:
370
- if len(messages) > 0 and messages[0]["role"] != "system" and len(tools_string.strip()) > 0:
371
- messages.insert(0, {"role": "system", "content": ""})
372
- return [message_format(msg, system_suffix=tools_string, user_prefix="") for msg in messages]
373
- else:
374
- return [message_format(msg, system_suffix="", user_prefix=tools_string) for msg in messages]
375
-
376
-
377
- # This is a modified version of
378
- # https://github.com/ShishirPatil/gorilla/blob/main/berkeley-function-call-leaderboard/bfcl/model_handler/utils.py
379
- # Thanks to the gorilla team for the original implementation
380
- def resolve_ast_call(elem):
381
- # Handle nested attributes for deeply nested module paths
382
- func_parts = []
383
- func_part = elem.func
384
- while isinstance(func_part, ast.Attribute):
385
- func_parts.append(func_part.attr)
386
- func_part = func_part.value
387
- if isinstance(func_part, ast.Name):
388
- func_parts.append(func_part.id)
389
- func_name = ".".join(reversed(func_parts))
390
- args_dict = {}
391
- for arg in elem.keywords:
392
- output = resolve_ast_by_type(arg.value)
393
- args_dict[arg.arg] = output
394
- return {func_name: args_dict}
395
-
396
-
397
- def resolve_ast_by_type(value):
398
- if isinstance(value, ast.Constant):
399
- if value.value is Ellipsis:
400
- output = "..."
401
- else:
402
- output = value.value
403
- elif isinstance(value, ast.UnaryOp):
404
- output = -value.operand.value
405
- elif isinstance(value, ast.List):
406
- output = [resolve_ast_by_type(v) for v in value.elts]
407
- elif isinstance(value, ast.Dict):
408
- output = {resolve_ast_by_type(k): resolve_ast_by_type(v) for k, v in zip(value.keys, value.values)}
409
- elif isinstance(value, ast.NameConstant): # Added this condition to handle boolean values
410
- output = value.value
411
- elif isinstance(value, ast.BinOp): # Added this condition to handle function calls as arguments
412
- output = eval(ast.unparse(value))
413
- elif isinstance(value, ast.Name):
414
- output = value.id
415
- elif isinstance(value, ast.Call):
416
- if len(value.keywords) == 0:
417
- output = ast.unparse(value)
418
- else:
419
- output = resolve_ast_call(value)
420
- elif isinstance(value, ast.Tuple):
421
- output = tuple(resolve_ast_by_type(v) for v in value.elts)
422
- elif isinstance(value, ast.Lambda):
423
- output = eval(ast.unparse(value.body[0].value))
424
- elif isinstance(value, ast.Ellipsis):
425
- output = "..."
426
- elif isinstance(value, ast.Subscript):
427
- try:
428
- output = ast.unparse(value.body[0].value)
429
- except:
430
- output = ast.unparse(value.value) + "[" + ast.unparse(value.slice) + "]"
431
- else:
432
- raise Exception(f"Unsupported AST type: {type(value)}")
433
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tokenizer_config.json CHANGED
@@ -1,10 +1,4 @@
1
  {
2
- "auto_map": {
3
- "AutoTokenizer": [
4
- "tokenization_minicpm.MiniCPMTokenizer",
5
- null
6
- ]
7
- },
8
  "add_bos_token": false,
9
  "add_eos_token": false,
10
  "added_tokens_decoder": {
@@ -115,7 +109,7 @@
115
  "pad_token": null,
116
  "sp_model_kwargs": {},
117
  "spaces_between_special_tokens": false,
118
- "tokenizer_class": "MiniCPMTokenizer",
119
  "unk_token": "<unk>",
120
  "use_default_system_prompt": false,
121
  "chat_template": "{%- macro json_to_python_type(param_name, json_spec) %}\n{%- set basic_type_map = {\n 'string': 'str',\n 'number': 'float',\n 'integer': 'int',\n 'boolean': 'bool',\n 'null': 'None'\n} %}\n\n{%- if json_spec.enum %}\n {{- param_name|title }}\n{%- elif basic_type_map[json_spec.type] is defined %}\n {{- basic_type_map[json_spec.type] }}\n{%- elif json_spec.type == 'array' %}\n {{- 'List[' + json_to_python_type(param_name, json_spec['items']) + ']' }}\n{%- elif json_spec.type == 'object' %}\n {{- 'Dict[str, ' + json_to_python_type(param_name, json_spec.additionalProperties if json_spec.additionalProperties else 'Any') + ']' if not json_spec.properties else param_name|title }}\n{%- elif json_spec.type is iterable %}\n {{- 'Union[' }}\n {%- for t in json_spec.type %}\n {{- json_to_python_type(param_name, {'type': t}) }}\n {{- ', ' if not loop.last }}\n {%- endfor %}\n {{- ']' }}\n{%- else %}\n {{- 'Any' }}\n{%- endif %}\n{%- endmacro %}\n\n{%- macro object_to_fields(json_spec, field_indent) %}\n {%- set o_ns = namespace(f = caller()) %}\n {%- for param_name, param_fields in json_spec.properties|items %}\n {%- if param_fields.enum %}\n {{- '\\n\\nclass ' + param_name|title + '(Enum):\\n' }}\n {%- for enum_option in param_fields.enum %}\n {{- ' enum_' + loop.index0|string + ' = ' + enum_option|tojson + '\\n' }}\n {%- endfor %}\n {%- elif param_fields.type == 'object' and param_fields.properties %}\n {%- call object_to_fields(param_fields, ' ') %}\n {{- '\\n\\nclass ' + param_name|title + '(BaseModel):\\n' }}\n {%- endcall %}\n {%- elif param_fields.type == 'array' and param_fields['items'] and param_fields['items'].type == 'object' and param_fields['items'].properties %}\n {%- call object_to_fields(param_fields['items'], ' ') %}\n {{- '\\n\\nclass ' + param_name|title + '(BaseModel):\\n' }}\n {%- endcall %}\n {%- endif %}\n {%- set param_default = param_fields.default|tojson if param_fields.default is string else param_fields.default|string if param_fields.default is defined else 'None' %}\n {%- set o_ns.f = o_ns.f + field_indent + param_name + ': ' %}\n {%- set o_ns.f = o_ns.f + ('Optional[' + json_to_python_type(param_name, param_fields) + ']' if param_name not in json_spec.required else json_to_python_type(param_name, param_fields)) %}\n {%- if not param_fields.title and not param_fields.description and not param_fields.pattern %}\n {%- set o_ns.f = o_ns.f + (' = ' + param_default if param_name not in json_spec.required else '') %}\n {%- else %}\n {%- set o_ns.f = o_ns.f + (' = Field(...' if param_name in json_spec.required else ' = Field(' + param_default) %}\n {%- set o_ns.f = o_ns.f + (', description=' + param_fields.description|tojson if param_fields.description else '') %}\n {%- set o_ns.f = o_ns.f + (', regex=' + param_fields.pattern|tojson if param_fields.pattern else '') %}\n {%- set o_ns.f = o_ns.f + (', title=' + param_fields.title|tojson if param_fields.title else '') %}\n {%- set o_ns.f = o_ns.f + ')' %}\n {%- endif %}\n {%- set o_ns.f = o_ns.f + '\\n' %}\n {%- endfor %}\n {{- o_ns.f }}\n{%- endmacro %}\n\n{%- macro tool_parser(tools) %}\n{%- for tool in tools %}\n {%- if tool.type is not defined or tool.type == 'function' %}\n {%- if tool.function is defined %}\n {%- set tool = tool.function %}\n {%- endif %}\n {%- set tool_params = tool.parameters if tool.parameters is defined else none %}\n {%- call object_to_fields(tool_params, ' ') %}\n {{- '\\n\\ndef ' + tool.name + '(' }}\n {%- if tool_params %}\n {%- for param_name, param_fields in tool_params.properties|items %}\n {%- set param_default = param_fields.default|tojson if param_fields.default is string else param_fields.default|string if param_fields.default is defined else 'None' %}\n {{- ', ' if loop.index0 != 0 }}\n {{- param_name }}\n {{- '=' + param_default if param_name not in tool_params.required }}\n {%- endfor %}\n {%- endif %}\n {{- '):\\n \"\"\"' }}\n {{- tool.description }}\n {{- '\\n\\n Args:\\n' if tool_params else '\\n' }}\n {%- endcall %}\n {{- ' \"\"\"\\n' }}\n {%- endif %}\n{%- endfor %}\n{%- endmacro %}\n\n{%- if messages[0]['role'] == 'system' %}\n {%- set loop_messages = messages[1:] %}\n {%- set system_message = messages[0]['content'] %}\n{%- else %}\n {%- set loop_messages = messages %}\n {%- set system_message = '' %}\n{%- endif %}\n{{- '<|im_start|>system\\n' + system_message if system_message or tools }}\n{%- if tools %}\n {{- '\\n# Functions\\nHere is a list of functions that you can invoke:\\n```python\\nfrom enum import Enum\\nfrom typing import List, Dict, Optional\\nfrom pydantic import BaseModel, Field\\n\\n' }}\n {{- tool_parser(tools) }}\n {{- \"\\n```\\n\\n# Function Call Rule and Output Format\\n- If the user's question can be answered without calling any function, please answer the user's question directly. In this situation, you should return your thought and answer the user's question directly.\\n- If the user cannot be answered without calling any function, and the user does not provide enough information to call functions, please ask the user for more information. In this situation, you should return your thought and ask the user for more information.\\n- If the user's question cannot be answered without calling any function, and the user has provided enough information to call functions to solve it, you should call the functions. In this situation, the assistant should return your thought and call the functions.\\n- Use default parameters unless the user has specified otherwise.\\n- You should answer in the following format:\\n\\n<|thought_start|>\\n{explain why the user's question can be answered without calling a function or why you should ask the user for more information or why you should call one or more functions and your plan to solve the user's question.}\\n<|thought_end|>\\n<|tool_call_start|>\\n```python\\nfunc1(params_name=params_value, params_name2=params_value2...)\\nfunc2(params)\\n```\\n<|tool_call_end|>\\n{answer the user's question directly or ask the user for more information}\" }}\n{%- endif %}\n{{- '<|im_end|>\\n' if system_message or tools }}\n{%- for message in loop_messages %}\n {%- set content = message.content %}\n {%- if message.role == 'assistant' and message.tool_calls %}\n {{- '<|im_start|>' + message.role + '\\n' }}\n {{- '<|thought_start|>\\n' + message.thought + '\\n<|thought_end|>\\n' if message.thought }}\n {{- '<|tool_call_start|>\\n```python\\n' }}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- tool_call.name + '(' }}\n {%- if tool_call.arguments is defined and tool_call.arguments|length > 0 %}\n {%- for param_name, param_value in tool_call.arguments|items %}\n {{- param_name + '=' + param_value|tojson }}\n {{- ',' if not loop.last }}\n {%- endfor %}\n {%- endif %}\n {{- ')\\n' }}\n {%- endfor %}\n {{- '```\\n<|tool_call_end|>\\n' }}\n {{- content if content and not content.startswith('<|tool_call_start|>') }}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == 'assistant' and message.thought %}\n {{- '<|im_start|>' + message.role + '\\n' + '<|thought_start|>\\n' + message.thought + '\\n<|thought_end|>\\n' + content + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endfor %}\n\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}"
 
1
  {
 
 
 
 
 
 
2
  "add_bos_token": false,
3
  "add_eos_token": false,
4
  "added_tokens_decoder": {
 
109
  "pad_token": null,
110
  "sp_model_kwargs": {},
111
  "spaces_between_special_tokens": false,
112
+ "tokenizer_class": "LlamaTokenizer",
113
  "unk_token": "<unk>",
114
  "use_default_system_prompt": false,
115
  "chat_template": "{%- macro json_to_python_type(param_name, json_spec) %}\n{%- set basic_type_map = {\n 'string': 'str',\n 'number': 'float',\n 'integer': 'int',\n 'boolean': 'bool',\n 'null': 'None'\n} %}\n\n{%- if json_spec.enum %}\n {{- param_name|title }}\n{%- elif basic_type_map[json_spec.type] is defined %}\n {{- basic_type_map[json_spec.type] }}\n{%- elif json_spec.type == 'array' %}\n {{- 'List[' + json_to_python_type(param_name, json_spec['items']) + ']' }}\n{%- elif json_spec.type == 'object' %}\n {{- 'Dict[str, ' + json_to_python_type(param_name, json_spec.additionalProperties if json_spec.additionalProperties else 'Any') + ']' if not json_spec.properties else param_name|title }}\n{%- elif json_spec.type is iterable %}\n {{- 'Union[' }}\n {%- for t in json_spec.type %}\n {{- json_to_python_type(param_name, {'type': t}) }}\n {{- ', ' if not loop.last }}\n {%- endfor %}\n {{- ']' }}\n{%- else %}\n {{- 'Any' }}\n{%- endif %}\n{%- endmacro %}\n\n{%- macro object_to_fields(json_spec, field_indent) %}\n {%- set o_ns = namespace(f = caller()) %}\n {%- for param_name, param_fields in json_spec.properties|items %}\n {%- if param_fields.enum %}\n {{- '\\n\\nclass ' + param_name|title + '(Enum):\\n' }}\n {%- for enum_option in param_fields.enum %}\n {{- ' enum_' + loop.index0|string + ' = ' + enum_option|tojson + '\\n' }}\n {%- endfor %}\n {%- elif param_fields.type == 'object' and param_fields.properties %}\n {%- call object_to_fields(param_fields, ' ') %}\n {{- '\\n\\nclass ' + param_name|title + '(BaseModel):\\n' }}\n {%- endcall %}\n {%- elif param_fields.type == 'array' and param_fields['items'] and param_fields['items'].type == 'object' and param_fields['items'].properties %}\n {%- call object_to_fields(param_fields['items'], ' ') %}\n {{- '\\n\\nclass ' + param_name|title + '(BaseModel):\\n' }}\n {%- endcall %}\n {%- endif %}\n {%- set param_default = param_fields.default|tojson if param_fields.default is string else param_fields.default|string if param_fields.default is defined else 'None' %}\n {%- set o_ns.f = o_ns.f + field_indent + param_name + ': ' %}\n {%- set o_ns.f = o_ns.f + ('Optional[' + json_to_python_type(param_name, param_fields) + ']' if param_name not in json_spec.required else json_to_python_type(param_name, param_fields)) %}\n {%- if not param_fields.title and not param_fields.description and not param_fields.pattern %}\n {%- set o_ns.f = o_ns.f + (' = ' + param_default if param_name not in json_spec.required else '') %}\n {%- else %}\n {%- set o_ns.f = o_ns.f + (' = Field(...' if param_name in json_spec.required else ' = Field(' + param_default) %}\n {%- set o_ns.f = o_ns.f + (', description=' + param_fields.description|tojson if param_fields.description else '') %}\n {%- set o_ns.f = o_ns.f + (', regex=' + param_fields.pattern|tojson if param_fields.pattern else '') %}\n {%- set o_ns.f = o_ns.f + (', title=' + param_fields.title|tojson if param_fields.title else '') %}\n {%- set o_ns.f = o_ns.f + ')' %}\n {%- endif %}\n {%- set o_ns.f = o_ns.f + '\\n' %}\n {%- endfor %}\n {{- o_ns.f }}\n{%- endmacro %}\n\n{%- macro tool_parser(tools) %}\n{%- for tool in tools %}\n {%- if tool.type is not defined or tool.type == 'function' %}\n {%- if tool.function is defined %}\n {%- set tool = tool.function %}\n {%- endif %}\n {%- set tool_params = tool.parameters if tool.parameters is defined else none %}\n {%- call object_to_fields(tool_params, ' ') %}\n {{- '\\n\\ndef ' + tool.name + '(' }}\n {%- if tool_params %}\n {%- for param_name, param_fields in tool_params.properties|items %}\n {%- set param_default = param_fields.default|tojson if param_fields.default is string else param_fields.default|string if param_fields.default is defined else 'None' %}\n {{- ', ' if loop.index0 != 0 }}\n {{- param_name }}\n {{- '=' + param_default if param_name not in tool_params.required }}\n {%- endfor %}\n {%- endif %}\n {{- '):\\n \"\"\"' }}\n {{- tool.description }}\n {{- '\\n\\n Args:\\n' if tool_params else '\\n' }}\n {%- endcall %}\n {{- ' \"\"\"\\n' }}\n {%- endif %}\n{%- endfor %}\n{%- endmacro %}\n\n{%- if messages[0]['role'] == 'system' %}\n {%- set loop_messages = messages[1:] %}\n {%- set system_message = messages[0]['content'] %}\n{%- else %}\n {%- set loop_messages = messages %}\n {%- set system_message = '' %}\n{%- endif %}\n{{- '<|im_start|>system\\n' + system_message if system_message or tools }}\n{%- if tools %}\n {{- '\\n# Functions\\nHere is a list of functions that you can invoke:\\n```python\\nfrom enum import Enum\\nfrom typing import List, Dict, Optional\\nfrom pydantic import BaseModel, Field\\n\\n' }}\n {{- tool_parser(tools) }}\n {{- \"\\n```\\n\\n# Function Call Rule and Output Format\\n- If the user's question can be answered without calling any function, please answer the user's question directly. In this situation, you should return your thought and answer the user's question directly.\\n- If the user cannot be answered without calling any function, and the user does not provide enough information to call functions, please ask the user for more information. In this situation, you should return your thought and ask the user for more information.\\n- If the user's question cannot be answered without calling any function, and the user has provided enough information to call functions to solve it, you should call the functions. In this situation, the assistant should return your thought and call the functions.\\n- Use default parameters unless the user has specified otherwise.\\n- You should answer in the following format:\\n\\n<|thought_start|>\\n{explain why the user's question can be answered without calling a function or why you should ask the user for more information or why you should call one or more functions and your plan to solve the user's question.}\\n<|thought_end|>\\n<|tool_call_start|>\\n```python\\nfunc1(params_name=params_value, params_name2=params_value2...)\\nfunc2(params)\\n```\\n<|tool_call_end|>\\n{answer the user's question directly or ask the user for more information}\" }}\n{%- endif %}\n{{- '<|im_end|>\\n' if system_message or tools }}\n{%- for message in loop_messages %}\n {%- set content = message.content %}\n {%- if message.role == 'assistant' and message.tool_calls %}\n {{- '<|im_start|>' + message.role + '\\n' }}\n {{- '<|thought_start|>\\n' + message.thought + '\\n<|thought_end|>\\n' if message.thought }}\n {{- '<|tool_call_start|>\\n```python\\n' }}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- tool_call.name + '(' }}\n {%- if tool_call.arguments is defined and tool_call.arguments|length > 0 %}\n {%- for param_name, param_value in tool_call.arguments|items %}\n {{- param_name + '=' + param_value|tojson }}\n {{- ',' if not loop.last }}\n {%- endfor %}\n {%- endif %}\n {{- ')\\n' }}\n {%- endfor %}\n {{- '```\\n<|tool_call_end|>\\n' }}\n {{- content if content and not content.startswith('<|tool_call_start|>') }}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == 'assistant' and message.thought %}\n {{- '<|im_start|>' + message.role + '\\n' + '<|thought_start|>\\n' + message.thought + '\\n<|thought_end|>\\n' + content + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endfor %}\n\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}"