|
| 1 | +import json |
| 2 | +from textwrap import dedent |
| 3 | +import outlines |
| 4 | +from outlines.samplers import greedy |
| 5 | +from transformers import AutoTokenizer, logging |
| 6 | +import warnings |
| 7 | +from constants import MODEL_NAME, DEVICE, T_TYPE |
| 8 | + |
| 9 | + |
| 10 | +logging.set_verbosity_error() |
| 11 | + |
| 12 | +def format_functions(functions): |
| 13 | + formatted_functions = [] |
| 14 | + for func in functions: |
| 15 | + function_info = f"{func['name']}: {func['description']}\n" |
| 16 | + if 'parameters' in func and 'properties' in func['parameters']: |
| 17 | + for arg, details in func['parameters']['properties'].items(): |
| 18 | + description = details.get('description', 'No description provided') |
| 19 | + function_info += f"- {arg}: {description}\n" |
| 20 | + formatted_functions.append(function_info) |
| 21 | + return "\n".join(formatted_functions) |
| 22 | + |
| 23 | +SYSTEM_PROMPT_FOR_CHAT_MODEL = dedent(""" |
| 24 | + You are an expert designed to call the correct function to solve a problem based on the user's request. |
| 25 | + The functions available (with required parameters) to you are: |
| 26 | + {functions} |
| 27 | + |
| 28 | + You will be given a user prompt and you need to decide which function to call. |
| 29 | + You will then need to format the function call correctly and return it in the correct format. |
| 30 | + The format for the function call is: |
| 31 | + [func1(params_name=params_value] |
| 32 | + NO other text MUST be included. |
| 33 | + |
| 34 | + For example: |
| 35 | + Request: I want to order a cheese pizza from Pizza Hut. |
| 36 | + Response: [order_food(restaurant="Pizza Hut", item="cheese pizza", quantity=1)] |
| 37 | + |
| 38 | + Request: Is it raining in NY. |
| 39 | + Response: [get_weather(city="New York")] |
| 40 | +
|
| 41 | + Request: I need a ride to SFO. |
| 42 | + Response: [order_ride(destination="SFO")] |
| 43 | + |
| 44 | + Request: I want to send a text to John saying Hello. |
| 45 | + Response: [send_text(to="John", message="Hello!")] |
| 46 | +""") |
| 47 | + |
| 48 | + |
| 49 | +ASSISTANT_PROMPT_FOR_CHAT_MODEL = dedent(""" |
| 50 | + I understand and will only return the function call in the correct format. |
| 51 | + """ |
| 52 | +) |
| 53 | +USER_PROMPT_FOR_CHAT_MODEL = dedent(""" |
| 54 | + Request: {user_prompt}. |
| 55 | +""") |
| 56 | + |
| 57 | +def continue_prompt(question, functions, tokenizer): |
| 58 | + prompt = SYSTEM_PROMPT_FOR_CHAT_MODEL.format(functions=format_functions(functions)) |
| 59 | + prompt += "\n\n" |
| 60 | + prompt += USER_PROMPT_FOR_CHAT_MODEL.format(user_prompt=question) |
| 61 | + return prompt |
| 62 | + |
| 63 | +def instruct_prompt(question, functions, tokenizer): |
| 64 | + messages = [ |
| 65 | + {"role": "user", "content": SYSTEM_PROMPT_FOR_CHAT_MODEL.format(functions=format_functions(functions))}, |
| 66 | + {"role": "assistant", "content": ASSISTANT_PROMPT_FOR_CHAT_MODEL }, |
| 67 | + {"role": "user", "content": USER_PROMPT_FOR_CHAT_MODEL.format(user_prompt=question)}, |
| 68 | + ] |
| 69 | + fc_prompt = tokenizer.apply_chat_template(messages, tokenize=False) |
| 70 | + return fc_prompt |
| 71 | + |
| 72 | +INTEGER = r"(-)?(0|[1-9][0-9]*)" |
| 73 | +STRING_INNER = r'([^"\\\x00-\x1F\x7F-\x9F]|\\["\\])' |
| 74 | +# We'll limit this to just a max of 42 characters |
| 75 | +STRING = f'"{STRING_INNER}{{1,42}}"' |
| 76 | +# i.e. 1 is a not a float but 1.0 is. |
| 77 | +FLOAT = rf"({INTEGER})(\.[0-9]+)([eE][+-][0-9]+)?" |
| 78 | +BOOLEAN = r"(true|false)" |
| 79 | +NULL = r"null" |
| 80 | + |
| 81 | +simple_type_map = { |
| 82 | + "string": STRING, |
| 83 | + "any": STRING, |
| 84 | + "integer": INTEGER, |
| 85 | + "number": FLOAT, |
| 86 | + "float": FLOAT, |
| 87 | + "boolean": BOOLEAN, |
| 88 | + "null": NULL, |
| 89 | +} |
| 90 | + |
| 91 | +def build_dict_regex(props): |
| 92 | + out_re = r"\{" |
| 93 | + args_part = ", ".join( |
| 94 | + [f'"{prop}": ' + type_to_regex(props[prop]) for prop in props] |
| 95 | + ) |
| 96 | + return out_re + args_part + r"\}" |
| 97 | + |
| 98 | +def type_to_regex(arg_meta): |
| 99 | + arg_type = arg_meta["type"] |
| 100 | + if arg_type == "object": |
| 101 | + arg_type = "dict" |
| 102 | + if arg_type == "dict": |
| 103 | + try: |
| 104 | + result = build_dict_regex(arg_meta["properties"]) |
| 105 | + except KeyError: |
| 106 | + return "Definition does not contain 'properties' value." |
| 107 | + elif arg_type in ["array","tuple"]: |
| 108 | + pattern = type_to_regex(arg_meta["items"]) |
| 109 | + result = r"\[(" + pattern + ", ){0,8}" + pattern + r"\]" |
| 110 | + else: |
| 111 | + result = simple_type_map[arg_type] |
| 112 | + return result |
| 113 | + |
| 114 | +type_to_regex({ |
| 115 | + "type": "array", |
| 116 | + "items": {"type": "float"} |
| 117 | +}) |
| 118 | + |
| 119 | +def build_standard_fc_regex(function_data): |
| 120 | + out_re = r"\[" + function_data["name"] + r"\(" |
| 121 | + args_part = ", ".join( |
| 122 | + [ |
| 123 | + f"{arg}=" + type_to_regex(function_data["parameters"]["properties"][arg]) |
| 124 | + for arg in function_data["parameters"]["properties"] |
| 125 | + |
| 126 | + if arg in function_data["parameters"]["required"] |
| 127 | + ] |
| 128 | + ) |
| 129 | + optional_part = "".join( |
| 130 | + [ |
| 131 | + f"(, {arg}=" |
| 132 | + + type_to_regex(function_data["parameters"]["properties"][arg]) |
| 133 | + + r")?" |
| 134 | + for arg in function_data["parameters"]["properties"] |
| 135 | + if not (arg in function_data["parameters"]["required"]) |
| 136 | + ] |
| 137 | + ) |
| 138 | + return out_re + args_part + optional_part + r"\)]" |
| 139 | + |
| 140 | +def multi_function_fc_regex(fs): |
| 141 | + multi_regex = "|".join([ |
| 142 | + rf"({build_standard_fc_regex(f)})" for f in fs |
| 143 | + ]) |
| 144 | + return multi_regex |
| 145 | + |
| 146 | +def load_functions(path): |
| 147 | + with open(path, "r") as f: |
| 148 | + return json.load(f)['functions'] |
| 149 | + |
| 150 | +class SmolMind: |
| 151 | + def __init__(self, functions, model_name=MODEL_NAME,instruct=True,debug=False): |
| 152 | + self.model_name = model_name |
| 153 | + self.instruct = instruct |
| 154 | + self.debug = debug |
| 155 | + self.functions = functions |
| 156 | + self.fc_regex = multi_function_fc_regex(functions) |
| 157 | + self.model = outlines.models.transformers( |
| 158 | + model_name, |
| 159 | + device=DEVICE, |
| 160 | + model_kwargs={ |
| 161 | + "trust_remote_code": True, |
| 162 | + "torch_dtype": T_TYPE, |
| 163 | + }) |
| 164 | + self.tokenizer = AutoTokenizer.from_pretrained(model_name) |
| 165 | + self.generator = outlines.generate.regex(self.model, self.fc_regex, sampler=greedy()) |
| 166 | + |
| 167 | + def get_function_call(self, user_prompt): |
| 168 | + with warnings.catch_warnings(): |
| 169 | + warnings.simplefilter("ignore") |
| 170 | + if self.instruct: |
| 171 | + prompt = instruct_prompt(user_prompt, self.functions, self.tokenizer) |
| 172 | + else: |
| 173 | + prompt = continue_prompt(user_prompt, self.functions, self.tokenizer) |
| 174 | + response = self.generator(prompt) |
| 175 | + if self.debug: |
| 176 | + print(f"functions: {self.functions}") |
| 177 | + print(f"prompt: {prompt}") |
| 178 | + return response |
0 commit comments