RanchiZhao commited on
Commit
6db86f7
1 Parent(s): 5ec6583

Upload tokenization_minicpm.py

Browse files
Files changed (1) hide show
  1. tokenization_minicpm.py +431 -0
tokenization_minicpm.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import json
3
+ import keyword
4
+ import traceback
5
+ import uuid
6
+ from collections import deque
7
+ from copy import deepcopy
8
+ from logging import getLogger
9
+ from typing import Any, Dict, List, Optional, Union
10
+
11
+ from datamodel_code_generator import DataModelType
12
+ from datamodel_code_generator.format import PythonVersion
13
+ from datamodel_code_generator.model import get_data_model_types
14
+ from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
15
+ from jsonschema import Draft202012Validator, exceptions, validate
16
+
17
+ from transformers import LlamaTokenizer
18
+ from transformers.tokenization_utils_base import BatchEncoding
19
+ from transformers.utils import TensorType
20
+
21
+
22
+ logger = getLogger(__name__)
23
+
24
+
25
+ class MiniCPMTokenizer(LlamaTokenizer):
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.strip(),
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.strip(),
162
+ "role": "assistant",
163
+ "thought": thought_string,
164
+ }
165
+ else:
166
+ return {
167
+ "content": sequence.strip(),
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
+ msg["content"] = user_prefix + "\n" + msg["content"]
263
+ elif msg["role"] == "system":
264
+ msg["content"] = msg["content"] + "\n" + system_suffix
265
+ msg["content"] = msg["content"].strip()
266
+ return msg
267
+
268
+
269
+ def jsonschema_to_code(jsonschema: dict) -> str:
270
+ input_text = json.dumps(jsonschema)
271
+ data_model_types = get_data_model_types(
272
+ DataModelType.PydanticBaseModel,
273
+ PythonVersion.PY_310,
274
+ )
275
+ parser = JsonSchemaParser(
276
+ source=input_text,
277
+ data_model_type=data_model_types.data_model,
278
+ data_model_root_type=data_model_types.root_model,
279
+ data_model_field_type=data_model_types.field_model,
280
+ data_type_manager_type=data_model_types.data_type_manager,
281
+ target_python_version=PythonVersion.PY_310,
282
+ dump_resolve_reference_action=data_model_types.dump_resolve_reference_action,
283
+ field_constraints=True,
284
+ )
285
+ results = parser.parse()
286
+ return results
287
+
288
+
289
+ def transform_function(function: dict):
290
+ """turn json format of function into signature"""
291
+ params, default_params = [], []
292
+ for prop_name, prop in function["parameters"]["properties"].items():
293
+ if "default" in prop:
294
+ default_params.append(f'{prop_name}={repr(prop["default"])}')
295
+ elif prop_name not in function["parameters"].get("required", []):
296
+ default_params.append(f"{prop_name}={repr(None)}")
297
+ else:
298
+ params.append(prop_name)
299
+ ps = ", ".join(params + default_params)
300
+ res = "def {f_name}({ps}):\n".format(f_name=function["name"], ps=ps)
301
+ f_des = function.get("description", "")
302
+ content = jsonschema_to_code(function["parameters"])
303
+ if "class" in content:
304
+ i = content.index("class")
305
+ # print(content[:i])
306
+ content = content[i:]
307
+ classes, args = content.split("class Model(BaseModel):", 1)
308
+ lint_msg = f' """\n {f_des}\n Args:\n{args}\n """\n'
309
+ res += lint_msg
310
+ if len(classes) > 0:
311
+ res = classes + res
312
+ return res
313
+
314
+
315
+ def input_format(messages: List[Dict], tools: List[Dict], add_to_system=True):
316
+ """
317
+ Process the input messages, global_arguments, tools, tool_choice,
318
+ and convert it into a input string.
319
+ The global arguments and tools can not be both empty.
320
+ parameters:
321
+ messages: List[Dict]
322
+ the input messages
323
+ For example:
324
+ tools: List[Dict]
325
+ the tools list you can use
326
+ For example:
327
+ """
328
+ messages = deepcopy(messages)
329
+ tools = deepcopy(tools)
330
+ if tools is not None and len(tools) > 0:
331
+ header = (
332
+ "from enum import Enum\nfrom typing import List, Dict, Optional\nfrom pydantic import BaseModel, Field\n\n"
333
+ )
334
+ tools_string = header
335
+ for tool in tools:
336
+ try:
337
+ tools_string += "\n\n" + transform_function(tool)
338
+ except:
339
+ pass
340
+ tools_template = """# Functions
341
+ Here is a list of functions that you can invoke:
342
+ ```python
343
+ {tools}
344
+ ```
345
+
346
+ # Function Call Rule and Output Format
347
+ - 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.
348
+ - 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.
349
+ - 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.
350
+ - Use default parameters unless the user has specified otherwise.
351
+ - You should answer in the following format:
352
+
353
+ <|thought_start|>
354
+ {{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.}}
355
+ <|thought_end|>
356
+ <|tool_call_start|>
357
+ ```python
358
+ func1(params_name=params_value, params_name2=params_value2...)
359
+ func2(params)
360
+ ```
361
+ <|tool_call_end|>
362
+ {{answer the user's question directly or ask the user for more information}}
363
+ """
364
+ tools_string = tools_template.format(tools=tools_string).strip()
365
+ else:
366
+ tools_string = ""
367
+
368
+ if add_to_system:
369
+ return [message_format(msg, system_suffix=tools_string, user_prefix="") for msg in messages]
370
+ else:
371
+ return [message_format(msg, system_suffix="", user_prefix=tools_string) for msg in messages]
372
+
373
+
374
+ # This is a modified version of
375
+ # https://github.com/ShishirPatil/gorilla/blob/main/berkeley-function-call-leaderboard/bfcl/model_handler/utils.py
376
+ # Thanks to the gorilla team for the original implementation
377
+ def resolve_ast_call(elem):
378
+ # Handle nested attributes for deeply nested module paths
379
+ func_parts = []
380
+ func_part = elem.func
381
+ while isinstance(func_part, ast.Attribute):
382
+ func_parts.append(func_part.attr)
383
+ func_part = func_part.value
384
+ if isinstance(func_part, ast.Name):
385
+ func_parts.append(func_part.id)
386
+ func_name = ".".join(reversed(func_parts))
387
+ args_dict = {}
388
+ for arg in elem.keywords:
389
+ output = resolve_ast_by_type(arg.value)
390
+ args_dict[arg.arg] = output
391
+ return {func_name: args_dict}
392
+
393
+
394
+ def resolve_ast_by_type(value):
395
+ if isinstance(value, ast.Constant):
396
+ if value.value is Ellipsis:
397
+ output = "..."
398
+ else:
399
+ output = value.value
400
+ elif isinstance(value, ast.UnaryOp):
401
+ output = -value.operand.value
402
+ elif isinstance(value, ast.List):
403
+ output = [resolve_ast_by_type(v) for v in value.elts]
404
+ elif isinstance(value, ast.Dict):
405
+ output = {resolve_ast_by_type(k): resolve_ast_by_type(v) for k, v in zip(value.keys, value.values)}
406
+ elif isinstance(value, ast.NameConstant): # Added this condition to handle boolean values
407
+ output = value.value
408
+ elif isinstance(value, ast.BinOp): # Added this condition to handle function calls as arguments
409
+ output = eval(ast.unparse(value))
410
+ elif isinstance(value, ast.Name):
411
+ output = value.id
412
+ elif isinstance(value, ast.Call):
413
+ if len(value.keywords) == 0:
414
+ output = ast.unparse(value)
415
+ else:
416
+ output = resolve_ast_call(value)
417
+ elif isinstance(value, ast.Tuple):
418
+ output = tuple(resolve_ast_by_type(v) for v in value.elts)
419
+ elif isinstance(value, ast.Lambda):
420
+ output = eval(ast.unparse(value.body[0].value))
421
+ elif isinstance(value, ast.Ellipsis):
422
+ output = "..."
423
+ elif isinstance(value, ast.Subscript):
424
+ try:
425
+ output = ast.unparse(value.body[0].value)
426
+ except:
427
+ output = ast.unparse(value.value) + "[" + ast.unparse(value.slice) + "]"
428
+ else:
429
+ raise Exception(f"Unsupported AST type: {type(value)}")
430
+ return output
431
+