Views
No views yet

| Model | Functionality |
|---|---|
| zefiro-funcioncalling-v0.3-alpha | Given a function, and user intent, returns properly formatted json with the right arguments |
!pip install openai==0.28.1, transformers1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3model_id = "mii-community/zefiro-functioncalling-v0.3-alpha"
4model = AutoModelForCausalLM.from_pretrained(model_id)
5model.to('cuda')
6tokenizer = AutoTokenizer.from_pretrained(model_id)
71json_arr = [{"name": "order_dinner", "description": "Ordina una cena al ristorante", "parameters": {"type": "object", "properties": {"restaurant_name": {"type": "string", "description": "il nome del ristorante", "enum" : ['Bufalo Bill','Pazzas']}}, "required": ["restaurant_name"]}},
2 {"name": "get_weather", "description": "Ottieni le previsioni del tempo meteorologica", "parameters": {"type": "object", "properties": {"location": {"type": "string", "description": "Il nome del luogo "}}, "required": ["location"]}},
3 {"name": "create_product", "description": "Crea un prodotto da vendere", "parameters": {"type": "object", "properties": {"product_name": {"type": "string", "description": "Il nome del prodotto "}, "size": {"type": "string", "description": "la taglia del prodotto"}, "price": {"type": "integer", "description": "Il prezzo del prodotto "}}, "required": ["product_name", "size", "price"]}},
4 {"name": "get_news", "description": "Dammi le ultime notizie", "parameters": {"type": "object", "properties": {"argument": {"type": "string", "description": "L'argomento su cui fare la ricerca"}}, "required": ["argument"]}},
5 ]
6json_string = ' '.join([json.dumps(json_obj) for json_obj in json_arr])
7system_prompt = 'Tu sei un assistenze utile che ha accesso alle seguenti funzioni. Usa le funzioni solo se necessario - \n ' + json_string + ' \n '
8print(system_prompt)
9
10test_message = [{'role' : 'system' , 'content' : system_prompt2},
11 {'role' : 'user' ,'content' : 'Crea un prodotto di nome AIR size L price 100'}]1def generate_text():
2 prompt = tokenizer.apply_chat_template(test_message, tokenize=False)
3 model_inputs = tokenizer([prompt], return_tensors="pt").to("cuda")
4 generated_ids = model.generate(**model_inputs, max_new_tokens=1024)
5 return tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
6
7
8text_response = generate_text()1FN_CALL_DELIMITER = "<<functioncall>>"
2
3def strip_function_calls(content: str) -> list[str]:
4 """
5 Split the content by the function call delimiter and remove empty strings
6 """
7 return [element.replace('\n', '') for element in content.split(FN_CALL_DELIMITER)[1:] if element ]
8
9
10functions_string = strip_function_calls(text_response)
11
12# Output: [' {"name": "create_product", "arguments": \'{"product_name": "AIR", "size": "L", "price": 100}\'}']1# if functions_string contains a function string create a json cleaning
2# multiple functions not supported yet
3if functions_string:
4 obj_to_call = json.loads(functions_string[0].replace('\'', ''))
5else:
6 print('nothing to do or return a normal chat response')
7
8# Output: {'name': 'create_product', 'arguments': {'product_name': 'AIR', 'size': 'L', 'price': 100}}1def obj_to_func(obj):
2 arguments_keys = obj['arguments'].keys()
3 params = []
4 for key in arguments_keys:
5 param = f'{key}=\"{obj["arguments"][key]}\"'
6 params.append(param)
7 func_params = ','.join(params)
8 print(f'{obj["name"]}({func_params})')
9 return f'{obj["name"]}({func_params})'
10
11func_str = obj_to_func(obj_to_call)
12
13openai_response = {
14 "index": 0,
15 "message": {
16 "role": "assistant",
17 "content": func_str,
18 "function_call": [
19 obj_to_call
20 ]
21 },
22 "finish_reason": "stop"
23}
24
25
26'''
27Output OpenAI compatible Dictionary
28{'index': 0,
29 'message': {
30 'role': 'assistant',
31 'content': 'create_product(product_name="AIR",size="L",price="100")',
32 'function_call': [{'name': 'create_product', 'arguments': {'product_name': 'AIR', 'size': 'L', 'price': 100}}]
33 },
34'finish_reason': 'stop'
35}
36'''