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25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import ast
import json
import keyword
import traceback
import uuid
from collections import deque
from logging import getLogger
from typing import Any, Dict, List, Optional, Union

from datamodel_code_generator import DataModelType
from datamodel_code_generator.format import PythonVersion
from datamodel_code_generator.model import get_data_model_types
from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
from jsonschema import Draft202012Validator, exceptions, validate

from transformers import LlamaTokenizerFast
from transformers.tokenization_utils_base import BatchEncoding
from transformers.utils import TensorType
from copy import deepcopy


logger = getLogger(__name__)


class MiniCPMTokenizer(LlamaTokenizerFast):
    def apply_chat_template(
        self,
        conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]]],
        tools: Optional[List[Dict]] = None,
        documents: Optional[List[Dict[str, str]]] = None,
        chat_template: Optional[str] = None,
        add_generation_prompt: bool = False,
        tokenize: bool = True,
        padding: bool = False,
        truncation: bool = False,
        max_length: Optional[int] = None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        return_dict: bool = False,
        return_assistant_tokens_mask: bool = False,
        tokenizer_kwargs: Optional[Dict[str, Any]] = None,
        **kwargs,
    ) -> Union[str, List[int], List[str], List[List[int]], BatchEncoding]:
        if tools is None:
            tools = []
        check_messages(conversation, tools)
        functions = [tool["function"] for tool in tools]
        conversation = self.reorder_tool_response(conversation)
        input_messages = input_format(conversation, functions, add_to_system=True)
        return super().apply_chat_template(
            input_messages,
            tools=None,
            documents=documents,
            chat_template=chat_template,
            add_generation_prompt=add_generation_prompt,
            tokenize=tokenize,
            padding=padding,
            truncation=truncation,
            max_length=max_length,
            return_tensors=return_tensors,
            return_dict=return_dict,
            return_assistant_tokens_mask=return_assistant_tokens_mask,
            tokenizer_kwargs=tokenizer_kwargs,
            **kwargs,
        )

    def reorder_tool_response(self, conversation: List[Dict[str, str]]):
        tool_call_ids = deque()
        tool_responses = deque()

        new_conversation = []
        for message in conversation:
            if (
                message["role"] == "assistant"
                and "tool_calls" in message
                and message["tool_calls"] is not None
                and len(message["tool_calls"]) > 0
            ):
                for tool_call in message["tool_calls"]:
                    tool_call_ids.append(tool_call["id"])
                new_conversation.append(message)
            elif message["role"] == "tool":
                tool_call_id = message.get("tool_call_id", None)
                if tool_call_id == tool_call_ids[0]:
                    new_conversation.append(message)
                    tool_call_ids.popleft()
                    while (
                        len(tool_call_ids) > 0
                        and len(tool_responses) > 0
                        and tool_call_ids[0] == tool_responses[0]["tool_call_id"]
                    ):
                        new_conversation.append(tool_responses.popleft())
                        tool_call_ids.popleft()
                else:
                    tool_responses.append(message)
            else:
                new_conversation.append(message)
        if len(tool_call_ids) != 0:
            raise ValueError(f"Message error, not all tool calls have responses: {tool_call_ids}")
        if len(tool_responses) != 0:
            raise ValueError(f"Message error, too many tool responses: {tool_responses}")
        return new_conversation

    def decode_function_call(
        self,
        sequence: str,
        tool_call_start="<|tool_call_start|>",
        tool_call_end="<|tool_call_end|>",
        thought_start="<|thought_start|>",
        thought_end="<|thought_end|>",
    ):
        if thought_end in sequence and thought_start in sequence:
            thought_string, sequence = sequence.rsplit(thought_end, 1)
            thought_string = thought_string.split(thought_start, 1)[1]
        else:
            thought_string = ""
        if tool_call_start in sequence and tool_call_end in sequence:
            tool_call_string, content = sequence.rsplit(tool_call_end, 1)
            tool_call_string = tool_call_string.split(tool_call_start, 1)[1]
            try:
                tool_calls = []
                tool_call_string = tool_call_string.strip()
                if tool_call_string.startswith("```"):
                    tool_call_string = tool_call_string.lstrip("```").strip()
                    if tool_call_string.startswith("python"):
                        tool_call_string = tool_call_string.lstrip("python").strip()
                if tool_call_string.endswith("```"):
                    tool_call_string = tool_call_string.rstrip("```").strip()
                for kw in keyword.kwlist:
                    tool_call_string = tool_call_string.replace("," + kw + "=", "," + kw + "_=")
                    tool_call_string = tool_call_string.replace(" " + kw + "=", " " + kw + "_=")
                    tool_call_string = tool_call_string.replace("(" + kw + "=", "(" + kw + "_=")

                parsed = ast.parse(tool_call_string)

                for elem in parsed.body:
                    assert isinstance(elem.value, ast.Call)
                    calls = resolve_ast_call(elem.value)

                    for func_name, func_args in calls.items():
                        new_args = {}
                        for k, v in func_args.items():
                            for kw in keyword.kwlist:
                                if k == kw + "_":
                                    k = kw
                            new_args[k] = v

                        this_one = {"name": func_name, "arguments": new_args}
                        tool_calls.append(this_one)

                return {
                    "content": content,
                    "tool_calls": [
                        {"type": "function", "function": tool_call, "id": "call_" + uuid.uuid4().hex}
                        for tool_call in tool_calls
                    ],
                    "role": "assistant",
                }
            except:
                logger.error(traceback.format_exc())
                return {
                    "content": content,
                    "role": "assistant",
                    "thought": thought_string,
                }
        else:
            return {
                "content": sequence,
                "role": "assistant",
                "thought": thought_string,
            }


def check_messages(conversation: List[Dict[str, str]], tools: List[Dict]):
    if tools is not None:
        for tool in tools:
            if "type" not in tool or tool["type"] != "function":
                raise ValueError(f"Tool {tool} is not valid")
            if "name" not in tool["function"]:
                raise ValueError(f"Tool {tool} is not valid")
            if "parameters" not in tool["function"] or not check_tool(tool["function"]["parameters"]["properties"]):
                raise ValueError(f"Tool {tool} is not valid")
    for message in conversation:
        if message["role"] == "assistant" and "tool_calls" in message and len(message["tool_calls"]) > 0:
            for tool_call in message["tool_calls"]:
                if "id" not in tool_call:
                    raise ValueError(f"Tool call {tool_call} is not valid")
                if tool_call["type"] != "function":
                    raise ValueError(f"Tool call {tool_call} is not valid")
                if "function" not in tool_call:
                    raise ValueError(f"Tool call {tool_call} is not valid")
                if not check_tool(tool_call["function"]):
                    raise ValueError(f"Tool call function {tool_call['function']} is not valid")
        elif message["role"] == "tool":
            if "tool_call_id" not in message:
                raise ValueError(f"Tool message {message['content']} is not valid")


def check_tool(tool_schema):
    try:
        Draft202012Validator.check_schema(tool_schema)
        return True
    except exceptions.SchemaError as e:
        print(f"SchemaError: {e}")
        return False


def check_args(args, tool_schema):
    try:
        validate(instance=args, schema=tool_schema)
        return True
    except exceptions.ValidationError as e:
        print(f"Data failed validation: {e}")
        return False


def message_format(msg, system_suffix="", user_prefix=""):
    if "thought" in msg and msg["thought"] is not None and len(msg["thought"]) > 0:
        thought_prefix = f"<|thought_start|>\n{msg['thought']}\n<|thought_end|>\n"
    else:
        thought_prefix = ""
    if msg["role"] == "assistant":
        content = msg.get("content", "")
        if content is None:
            content = ""
        if "tool_calls" in msg and msg["tool_calls"] is not None and len(msg["tool_calls"]) > 0:

            def add_quotes(variable):
                if isinstance(variable, str):
                    return repr(variable)
                else:
                    return str(variable)

            tool_calls = []
            for _tool_call in msg["tool_calls"]:
                if _tool_call is None:
                    continue
                tool_call = _tool_call["function"]
                tool_name = tool_call["name"]
                if "arguments" not in tool_call or tool_call["arguments"] is None:
                    continue
                if isinstance(tool_call["arguments"], str):
                    try:
                        tool_call["arguments"] = json.loads(tool_call["arguments"])
                    except:
                        continue
                args = ",".join([k + "=" + add_quotes(v) for k, v in tool_call["arguments"].items()])
                tool_calls.append(f"{tool_name}({args})")

            content = (
                thought_prefix
                + "<|tool_call_start|>\n```python\n"
                + "\n".join(tool_calls).strip()
                + "\n```\n<|tool_call_end|>\n"
                + content
            )
            # msg["tool_call_string"] = "\n".join(tool_calls).strip()
            msg["content"] = content
        else:
            content = thought_prefix + content
            msg["content"] = content
    elif msg["role"] == "user":
        if user_prefix != "":
            msg["content"] = user_prefix + "\n" + msg["content"]
    elif msg["role"] == "system":
        msg["content"] = msg["content"] + "\n" + system_suffix
    msg["content"] = msg["content"]
    return msg


def jsonschema_to_code(jsonschema: dict) -> str:
    input_text = json.dumps(jsonschema)
    data_model_types = get_data_model_types(
        DataModelType.PydanticBaseModel,
        PythonVersion.PY_310,
    )
    parser = JsonSchemaParser(
        source=input_text,
        data_model_type=data_model_types.data_model,
        data_model_root_type=data_model_types.root_model,
        data_model_field_type=data_model_types.field_model,
        data_type_manager_type=data_model_types.data_type_manager,
        target_python_version=PythonVersion.PY_310,
        dump_resolve_reference_action=data_model_types.dump_resolve_reference_action,
        field_constraints=True,
    )
    results = parser.parse()
    return results


def transform_function(function: dict):
    """turn json format of function into signature"""
    params, default_params = [], []
    for prop_name, prop in function["parameters"]["properties"].items():
        if "default" in prop:
            default_params.append(f'{prop_name}={repr(prop["default"])}')
        elif prop_name not in function["parameters"].get("required", []):
            default_params.append(f"{prop_name}={repr(None)}")
        else:
            params.append(prop_name)
    ps = ", ".join(params + default_params)
    res = "def {f_name}({ps}):\n".format(f_name=function["name"], ps=ps)
    f_des = function.get("description", "")
    content = jsonschema_to_code(function["parameters"])
    if "class" in content:
        i = content.index("class")
        # print(content[:i])
        content = content[i:]
    classes, args = content.split("class Model(BaseModel):", 1)
    lint_msg = f'    """\n    {f_des}\n    Args:\n{args}\n    """\n'
    res += lint_msg
    if len(classes) > 0:
        res = classes + res
    return res


def input_format(messages: List[Dict], tools: List[Dict], add_to_system=True):
    """
    Process the input messages, global_arguments, tools, tool_choice,
        and convert it into a input string.
    The global arguments and tools can not be both empty.
    parameters:
        messages: List[Dict]
            the input messages
            For example:
        tools: List[Dict]
            the tools list you can use
            For example:
    """
    messages = deepcopy(messages)
    tools = deepcopy(tools)
    if tools is not None and len(tools) > 0:
        header = (
            "from enum import Enum\nfrom typing import List, Dict, Optional\nfrom pydantic import BaseModel, Field\n\n"
        )
        tools_string = header
        for tool in tools:
            try:
                tools_string += "\n\n" + transform_function(tool)
            except:
                pass
        tools_template = """# Functions
Here is a list of functions that you can invoke:
```python
{tools}
```

# Function Call Rule and Output Format
- 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.
- 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.
- 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.
- Use default parameters unless the user has specified otherwise.
- You should answer in the following format:

<|thought_start|>
{{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.}}
<|thought_end|>
<|tool_call_start|>
```python
func1(params_name=params_value, params_name2=params_value2...)
func2(params)
```
<|tool_call_end|>
{{answer the user's question directly or ask the user for more information}}
"""
        tools_string = tools_template.format(tools=tools_string)
    else:
        tools_string = ""

    if add_to_system:
        if len(messages) > 0 and messages[0]["role"] != "system" and len(tools_string.strip()) > 0:
            messages.insert(0, {"role": "system", "content": ""})
        return [message_format(msg, system_suffix=tools_string, user_prefix="") for msg in messages]
    else:
        return [message_format(msg, system_suffix="", user_prefix=tools_string) for msg in messages]


# This is a modified version of
# https://github.com/ShishirPatil/gorilla/blob/main/berkeley-function-call-leaderboard/bfcl/model_handler/utils.py
# Thanks to the gorilla team for the original implementation
def resolve_ast_call(elem):
    # Handle nested attributes for deeply nested module paths
    func_parts = []
    func_part = elem.func
    while isinstance(func_part, ast.Attribute):
        func_parts.append(func_part.attr)
        func_part = func_part.value
    if isinstance(func_part, ast.Name):
        func_parts.append(func_part.id)
    func_name = ".".join(reversed(func_parts))
    args_dict = {}
    for arg in elem.keywords:
        output = resolve_ast_by_type(arg.value)
        args_dict[arg.arg] = output
    return {func_name: args_dict}


def resolve_ast_by_type(value):
    if isinstance(value, ast.Constant):
        if value.value is Ellipsis:
            output = "..."
        else:
            output = value.value
    elif isinstance(value, ast.UnaryOp):
        output = -value.operand.value
    elif isinstance(value, ast.List):
        output = [resolve_ast_by_type(v) for v in value.elts]
    elif isinstance(value, ast.Dict):
        output = {resolve_ast_by_type(k): resolve_ast_by_type(v) for k, v in zip(value.keys, value.values)}
    elif isinstance(value, ast.NameConstant):  # Added this condition to handle boolean values
        output = value.value
    elif isinstance(value, ast.BinOp):  # Added this condition to handle function calls as arguments
        output = eval(ast.unparse(value))
    elif isinstance(value, ast.Name):
        output = value.id
    elif isinstance(value, ast.Call):
        if len(value.keywords) == 0:
            output = ast.unparse(value)
        else:
            output = resolve_ast_call(value)
    elif isinstance(value, ast.Tuple):
        output = tuple(resolve_ast_by_type(v) for v in value.elts)
    elif isinstance(value, ast.Lambda):
        output = eval(ast.unparse(value.body[0].value))
    elif isinstance(value, ast.Ellipsis):
        output = "..."
    elif isinstance(value, ast.Subscript):
        try:
            output = ast.unparse(value.body[0].value)
        except:
            output = ast.unparse(value.value) + "[" + ast.unparse(value.slice) + "]"
    else:
        raise Exception(f"Unsupported AST type: {type(value)}")
    return output