Views
No views yet
! pip install transformers torch1from transformers import AutoTokenizer, AutoModelForCausalLM
2import torch
3import json
4
5# Khởi tạo tokenizer và model
6tokenizer = AutoTokenizer.from_pretrained("ricepaper/vi-gemma-2-2b-function-calling")
7model = AutoModelForCausalLM.from_pretrained(
8 "ricepaper/vi-gemma-2-2b-function-calling",
9 device_map="auto",
10 torch_dtype=torch.float16,
11)1def process_user_query(user_query, messages, available_tools):
2 """
3 Xử lý user query, tạo response, kiểm tra và thực thi function call (nếu có).
4
5 Args:
6 user_query (str): Query từ người dùng.
7 messages (list): List messages hiện tại trong conversation.
8 available_tools (dict): Dictionary chứa các function có sẵn.
9
10 Returns:
11 str: Response cuối cùng sau khi xử lý function call (nếu có).
12 """
13
14 # Thêm user query vào messages
15 messages.append({"role": "user", "content": user_query})
16
17 # Tạo response từ model
18 input_ids = tokenizer.apply_chat_template(
19 messages,
20 add_generation_prompt=True,
21 return_tensors="pt"
22 ).to(model.device)
23 outputs = model.generate(
24 input_ids,
25 max_new_tokens=300,
26 # ... (Các tham số generate khác)
27 )
28 response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)
29
30 try:
31 # Chuyển đổi chuỗi JSON thành list Python
32 response_list = json.loads(response)
33 # Thêm response vào messages nếu có functioncall
34 messages.append({"role": "assistant", "content": response})
35 except json.JSONDecodeError:
36 # Nếu response không phải JSON, coi như không có function call
37 response_list = []
38
39 # Khởi tạo list function_responses để lưu kết quả
40 function_responses = []
41
42 # Duyệt qua từng phần tử trong list
43 for response_dict in response_list:
44 if "name" in response_dict and "arguments" in response_dict:
45 function_name = response_dict.get("name")
46 function_args = response_dict.get("arguments")
47
48 if function_name in available_tools:
49 # Thực hiện function call
50 print(f"Calling function {function_name} with arguments {function_args}\n")
51 function_to_call = available_tools[function_name]
52 function_response = function_to_call(**function_args)
53
54 # Lưu kết quả dưới dạng dictionary
55 function_responses.append({
56 "name": function_name,
57 "response": function_response
58 })
59 else:
60 print(f"Function {function_name} not found")
61
62 # Thêm list function_responses vào messages
63 if function_responses:
64 messages.append({
65 "role": "user",
66 "content": f"FUNCTION RESPONSES:\n{json.dumps(function_responses, ensure_ascii=False)}"
67 })
68 print(messages[-1].get("content"))
69
70 # Tạo response mới sau khi xử lý function call
71 input_ids = tokenizer.apply_chat_template(
72 messages,
73 add_generation_prompt=True,
74 return_tensors="pt"
75 ).to(model.device)
76 outputs = model.generate(
77 input_ids,
78 max_new_tokens=300,
79 # ... (Các tham số generate khác)
80 )
81 response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)
82
83 return response1## Hàm mô phỏng hỗ trợ tính boa cho một hóa đơn
2def calculate_tip(bill_amount: float, tip_percentage: float) -> str:
3 """Tính số tiền boa cho một hóa đơn và trả về một chuỗi mô tả kết quả.
4
5 Args:
6 bill_amount: Tổng số tiền của hóa đơn.
7 tip_percentage: Tỷ lệ tiền boa.
8
9 Returns:
10 Một chuỗi mô tả số tiền boa và tổng số tiền phải trả.
11 """
12
13 tip_amount = bill_amount * (tip_percentage / 100)
14 total_amount = bill_amount + tip_amount
15 return f"Số tiền boa là: {tip_amount:.2f}\nTổng số tiền phải trả là: {total_amount:.2f}"
16
17# Khai báo danh sách tools
18tools = """
19{
20 "name": "calculate_tip",
21 "description": "Tính số tiền boa cho một hóa đơn",
22 "parameters": {
23 "type": "object",
24 "properties": {
25 "bill_amount": {
26 "type": "number",
27 "description": "Tổng số tiền của hóa đơn"
28 },
29 "tip_percentage": {
30 "type": "number",
31 "description": "Tỷ lệ tiền boa"
32 }
33 },
34 "required": [
35 "bill_amount",
36 "tip_percentage"
37 ]
38 }
39},
40"""
41
42# Tạo dictionary ánh xạ tên hàm với hàm tương ứng
43available_tools = {
44 "calculate_tip": calculate_tip,
45}1# Tạo lịch sử trò chuyện mới
2messages = [
3 {"role": "user", "content": f"""Bạn là một trợ lý hữu ích với quyền truy cập vào các chức năng sau. Sử dụng chúng nếu cần thiết {tools}"""},
4 {"role": "assistant", "content": "Xin chào, tôi có thể giúp gì cho bạn?"},
5]
6# Sử dụng
7res = process_user_query("Tôi cần trợ giúp tính tiền boa cho hóa đơn của mình. Tổng số tiền là 50 USD và tôi muốn để lại 15% tiền boa?", messages, available_tools)
8messages.append({"role": "assistant", "content": res})
9print("\n"+res)
10# Calling function calculate_tip with arguments {'bill_amount': 50, 'tip_percentage': 15}
11
12# FUNCTION RESPONSES:
13# [{"name": "calculate_tip", "response": "Số tiền boa là: 7.50\nTổng số tiền phải trả là: 57.50"}]
14
15# Số tiền boa cho hóa đơn của bạn là 7,50 USD. Tổng số tiền phải trả là 57,50 USD.
16
17messages
18# [{'role': 'user',
19# 'content': 'Bạn là một trợ lý hữu ích với quyền truy cập vào các chức năng sau. Sử dụng chúng nếu cần thiết \n{\n "name": "calculate_tip",\n "description": "Tính số tiền boa cho một hóa đơn",\n "parameters": {\n "type": "object",\n "properties": {\n "bill_amount": {\n "type": "number",\n "description": "Tổng số tiền của hóa đơn"\n },\n "tip_percentage": {\n "type": "number",\n "description": "Tỷ lệ tiền boa"\n }\n },\n "required": [\n "bill_amount",\n "tip_percentage"\n ]\n }\n},\n'},
20# {'role': 'assistant', 'content': 'Xin chào, tôi có thể giúp gì cho bạn?'},
21# {'role': 'user',
22# 'content': 'Tôi cần trợ giúp tính tiền boa cho hóa đơn của mình. Tổng số tiền là 50 USD và tôi muốn để lại 15% tiền boa?'},
23# {'role': 'assistant',
24# 'content': '[{"name": "calculate_tip", "arguments": {"bill_amount": 50, "tip_percentage": 15}}]'},
25# {'role': 'user',
26# 'content': 'FUNCTION RESPONSES:\n[{"name": "calculate_tip", "response": "Số tiền boa là: 7.50\\nTổng số tiền phải trả là: 57.50"}]'},
27# {'role': 'assistant',
28# 'content': 'Số tiền boa cho hóa đơn của bạn là 7,50 USD. Tổng số tiền phải trả là 57,50 USD.'}]! pip install transformers torch1from transformers import AutoTokenizer, AutoModelForCausalLM
2import torch
3import json
4
5# Initialize the tokenizer and model
6tokenizer = AutoTokenizer.from_pretrained("ricepaper/vi-gemma-2-2b-function-calling")
7model = AutoModelForCausalLM.from_pretrained(
8 "ricepaper/vi-gemma-2-2b-function-calling",
9 device_map="auto",
10 torch_dtype=torch.float16,
11)1def process_user_query(user_query, messages, available_tools):
2 """
3 Processes user queries, generates responses, checks for, and executes function calls (if any).
4
5 Args:
6 user_query (str): The query from the user.
7 messages (list): The list of current messages in the conversation.
8 available_tools (dict): A dictionary containing available functions.
9
10 Returns:
11 str: The final response after processing function calls (if any).
12 """
13
14 # Add the user query to the messages
15 messages.append({"role": "user", "content": user_query})
16
17 # Generate a response from the model
18 input_ids = tokenizer.apply_chat_template(
19 messages,
20 add_generation_prompt=True,
21 return_tensors="pt"
22 ).to(model.device)
23 outputs = model.generate(
24 input_ids,
25 max_new_tokens=300,
26 # ... (Other generate parameters)
27 )
28 response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)
29
30 try:
31 # Convert the JSON string to a Python list
32 response_list = json.loads(response)
33 # Add the response to messages if there's a function call
34 messages.append({"role": "assistant", "content": response})
35 except json.JSONDecodeError:
36 # If the response is not JSON, assume no function call
37 response_list = []
38
39 # Initialize a list to store function responses
40 function_responses = []
41
42 # Iterate through each element in the list
43 for response_dict in response_list:
44 if "name" in response_dict and "arguments" in response_dict:
45 function_name = response_dict.get("name")
46 function_args = response_dict.get("arguments")
47
48 if function_name in available_tools:
49 # Execute the function call
50 print(f"Calling function {function_name} with arguments {function_args}\n")
51 function_to_call = available_tools[function_name]
52 function_response = function_to_call(**function_args)
53
54 # Store the result as a dictionary
55 function_responses.append({
56 "name": function_name,
57 "response": function_response
58 })
59 else:
60 print(f"Function {function_name} not found")
61
62 # Add the list of function responses to the messages
63 if function_responses:
64 messages.append({
65 "role": "user",
66 "content": f"FUNCTION RESPONSES:\n{json.dumps(function_responses, ensure_ascii=False)}"
67 })
68 print(messages[-1].get("content"))
69
70 # Generate a new response after processing function calls
71 input_ids = tokenizer.apply_chat_template(
72 messages,
73 add_generation_prompt=True,
74 return_tensors="pt"
75 ).to(model.device)
76 outputs = model.generate(
77 input_ids,
78 max_new_tokens=300,
79 # ... (Other generate parameters)
80 )
81 response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)
82
83 return response1## Function simulating tip calculation for a bill
2def calculate_tip(bill_amount: float, tip_percentage: float) -> str:
3 """Calculates the tip amount for a bill and returns a string describing the result.
4
5 Args:
6 bill_amount: The total amount of the bill.
7 tip_percentage: The tip percentage.
8
9 Returns:
10 A string describing the tip amount and the total amount to be paid.
11 """
12
13 tip_amount = bill_amount * (tip_percentage / 100)
14 total_amount = bill_amount + tip_amount
15 return f"The tip amount is: {tip_amount:.2f}\nThe total amount to be paid is: {total_amount:.2f}"
16
17# Declare the tools list
18tools = """
19{
20 "name": "calculate_tip",
21 "description": "Calculate the tip amount for a bill",
22 "parameters": {
23 "type": "object",
24 "properties": {
25 "bill_amount": {
26 "type": "number",
27 "description": "The total bill amount"
28 },
29 "tip_percentage": {
30 "type": "number",
31 "description": "The tip percentage"
32 }
33 },
34 "required": [
35 "bill_amount",
36 "tip_percentage"
37 ]
38 }
39},
40"""
41
42# Create a dictionary mapping function names to their corresponding functions
43available_tools = {
44 "calculate_tip": calculate_tip,
45}1# Create a new conversation history
2messages = [
3 {"role": "user", "content": f"""You are a helpful assistant with access to the following functions. Use them if necessary {tools}"""},
4 {"role": "assistant", "content": "Hello, how can I assist you?"},
5]
6# Use the model
7res = process_user_query("I need help calculating the tip for my bill. The total is $50 and I would like to leave a 15% tip.", messages, available_tools)
8messages.append({"role": "assistant", "content": res})
9print("\n"+res)
10# Calling function calculate_tip with arguments {'bill_amount': 50, 'tip_percentage': 15}
11
12# FUNCTION RESPONSES:
13# [{"name": "calculate_tip", "response": "The tip amount is: 7.50\nThe total amount to be paid is: 57.50"}]
14
15# The tip amount for your bill is $7.50. The total amount to be paid is $57.50.
16
17messages
18# [{'role': 'user',
19# 'content': 'You are a helpful assistant with access to the following functions. Use them if necessary \n{\n "name": "calculate_tip",\n "description": "Calculate the tip amount for a bill",\n "parameters": {\n "type": "object",\n "properties": {\n "bill_amount": {\n "type": "number",\n "description": "The total bill amount"\n },\n "tip_percentage": {\n "type": "number",\n "description": "The tip percentage"\n }\n },\n "required": [\n "bill_amount",\n "tip_percentage"\n ]\n }\n},\n'},
20# {'role': 'assistant', 'content': 'Hello, how can I assist you?'},
21# {'role': 'user',
22# 'content': 'I need help calculating the tip for my bill. The total is $50 and I would like to leave a 15% tip.'},
23# {'role': 'assistant',
24# 'content': '[{"name": "calculate_tip", "arguments": {"bill_amount": 50, "tip_percentage": 15}}]'},
25# {'role': 'user',
26# 'content': 'FUNCTION RESPONSES:\n[{"name": "calculate_tip", "response": "The tip amount is: 7.50\\nThe total amount to be paid is: 57.50"}]'},
27# {'role': 'assistant',
28# 'content': 'The tip amount for your bill is $7.50. The total amount to be paid is $57.50.'}]