Edit model card

(English below)

Model Card cho ricepaper/vi-gemma-2-2b-function-calling

Mô tả Mô hình

ricepaper/vi-gemma-2-2b-function-calling là mô hình ngôn ngữ lớn được tinh chỉnh từ google/gemma-2-2b-it cho khả năng hiểu và thực thi single/multi function call (gọi hàm) tối ưu cho 2 ngôn ngữ chính: tiếng Việt và tiếng Anh. Mô hình được huấn luyện với tập dữ liệu phong phú bao gồm các đoạn hội thoại chứa function call theo định dạng ChatML, kết hợp với tập dữ liệu đa ngôn ngữ được dịch sang tiếng Việt.

Mục đích Sử dụng

Mô hình này phù hợp cho các ứng dụng yêu cầu:

  • Xây dựng chatbot có khả năng tương tác với người dùng và thực thi các tác vụ cụ thể thông qua function call.
  • Tạo các hệ thống hỏi đáp tự động có khả năng truy xuất thông tin từ các nguồn dữ liệu khác nhau.
  • Phát triển các ứng dụng xử lý ngôn ngữ tự nhiên nâng cao như tóm tắt văn bản, dịch máy, tạo văn bản.
  • Xây dựng agent: Tạo các agent thông minh có khả năng tương tác với môi trường và thực hiện các hành động dựa trên ngôn ngữ.
  • Hệ thống multi-agent: Phát triển các hệ thống đa tác tử, trong đó các agent có thể giao tiếp và hợp tác với nhau để giải quyết các vấn đề phức tạp.

Cách sử dụng

1. Cài đặt các thư viện cần thiết:

! pip install transformers torch

2. Khởi tạo tokenizer và model:

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import json

# Khởi tạo tokenizer và model
tokenizer = AutoTokenizer.from_pretrained("ricepaper/vi-gemma-2-2b-function-calling")
model = AutoModelForCausalLM.from_pretrained(
    "ricepaper/vi-gemma-2-2b-function-calling",
    device_map="auto",
    torch_dtype=torch.float16,
)

3. Xây dựng hàm xử lý user query:

def process_user_query(user_query, messages, available_tools):
    """
    Xử lý user query, tạo response, kiểm tra và thực thi function call (nếu có).

    Args:
        user_query (str): Query từ người dùng.
        messages (list): List messages hiện tại trong conversation.
        available_tools (dict): Dictionary chứa các function có sẵn.

    Returns:
        str: Response cuối cùng sau khi xử lý function call (nếu có).
    """

    # Thêm user query vào messages
    messages.append({"role": "user", "content": user_query})

    # Tạo response từ model
    input_ids = tokenizer.apply_chat_template(
        messages,
        add_generation_prompt=True,
        return_tensors="pt"
    ).to(model.device)
    outputs = model.generate(
        input_ids,
        max_new_tokens=300,
        # ... (Các tham số generate khác)
    )
    response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)

    try:
        # Chuyển đổi chuỗi JSON thành list Python
        response_list = json.loads(response)
        # Thêm response vào messages nếu có functioncall
        messages.append({"role": "assistant", "content": response})
    except json.JSONDecodeError:
        # Nếu response không phải JSON, coi như không có function call
        response_list = []

    # Khởi tạo list function_responses để lưu kết quả
    function_responses = []

    # Duyệt qua từng phần tử trong list
    for response_dict in response_list:
        if "name" in response_dict and "arguments" in response_dict:
            function_name = response_dict.get("name")
            function_args = response_dict.get("arguments")

            if function_name in available_tools:
                # Thực hiện function call
                print(f"Calling function {function_name} with arguments {function_args}\n")
                function_to_call = available_tools[function_name]
                function_response = function_to_call(**function_args)
                
                # Lưu kết quả dưới dạng dictionary
                function_responses.append({
                    "name": function_name,
                    "response": function_response
                })
            else:
                print(f"Function {function_name} not found")

    # Thêm list function_responses vào messages
    if function_responses:
        messages.append({
            "role": "user",
            "content": f"FUNCTION RESPONSES:\n{json.dumps(function_responses, ensure_ascii=False)}"
        })
        print(messages[-1].get("content"))

        # Tạo response mới sau khi xử lý function call
        input_ids = tokenizer.apply_chat_template(
            messages,
            add_generation_prompt=True,
            return_tensors="pt"
        ).to(model.device)
        outputs = model.generate(
            input_ids,
            max_new_tokens=300,
            # ... (Các tham số generate khác)
        )
        response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)

    return response

4. Tạo các hàm hỗ trợ và khai báo danh sách tools:

## Hàm mô phỏng hỗ trợ tính boa cho một hóa đơn
def calculate_tip(bill_amount: float, tip_percentage: float) -> str:
  """Tính số tiền boa cho một hóa đơn và trả về một chuỗi mô tả kết quả.

  Args:
    bill_amount: Tổng số tiền của hóa đơn.
    tip_percentage: Tỷ lệ tiền boa.

  Returns:
    Một chuỗi mô tả số tiền boa và tổng số tiền phải trả.
  """

  tip_amount = bill_amount * (tip_percentage / 100)
  total_amount = bill_amount + tip_amount
  return f"Số tiền boa là: {tip_amount:.2f}\nTổng số tiền phải trả là: {total_amount:.2f}"

# Khai báo danh sách tools
tools = """
{
  "name": "calculate_tip",
  "description": "Tính số tiền boa cho một hóa đơn",
  "parameters": {
    "type": "object",
    "properties": {
      "bill_amount": {
        "type": "number",
        "description": "Tổng số tiền của hóa đơn"
      },
      "tip_percentage": {
        "type": "number",
        "description": "Tỷ lệ tiền boa"
      }
    },
    "required": [
      "bill_amount",
      "tip_percentage"
    ]
  }
},
"""

# Tạo dictionary ánh xạ tên hàm với hàm tương ứng
available_tools = {
    "calculate_tip": calculate_tip,
}

5. Tạo lịch sử trò chuyện và sử dụng:

# Tạo lịch sử trò chuyện mới
messages = [
    {"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}"""},
    {"role": "assistant", "content": "Xin chào, tôi có thể giúp gì cho bạn?"},
]
# Sử dụng
res = 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)
messages.append({"role": "assistant", "content": res})
print("\n"+res)
# Calling function calculate_tip with arguments {'bill_amount': 50, 'tip_percentage': 15}

# FUNCTION RESPONSES:
# [{"name": "calculate_tip", "response": "Số tiền boa là: 7.50\nTổng số tiền phải trả là: 57.50"}]

# 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.

messages
# [{'role': 'user',
#   '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'},
#  {'role': 'assistant', 'content': 'Xin chào, tôi có thể giúp gì cho bạn?'},
#  {'role': 'user',
#   '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?'},
#  {'role': 'assistant',
#   'content': '[{"name": "calculate_tip", "arguments": {"bill_amount": 50, "tip_percentage": 15}}]'},
#  {'role': 'user',
#   '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"}]'},
#  {'role': 'assistant',
#   '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.'}]

Lưu ý

  • Mô hình có thể yêu cầu scale chất lượng và cấu hình phần cứng phù hợp để hoạt động hiệu quả.
  • Kết quả của function call phụ thuộc vào chất lượng của hàm hỗ trợ được cung cấp.
  • Người dùng có thể thay đổi các tham số generate của mô hình để điều chỉnh độ dài và nội dung của response.

English model card version:

Model Card for ricepaper/vi-gemma-2-2b-function-calling

Model Description

ricepaper/vi-gemma-2-2b-function-calling is a large language model fine-tuned from google/gemma-2-2b-it for understanding and executing single/multi function calls, optimized for 2 main languages: Vietnamese and English. The model is trained on a rich dataset of conversations containing function calls in ChatML format, combined with multilingual data translated into Vietnamese.

Intended Uses

This model is suitable for applications requiring:

  • Building chatbots that can interact with users and perform specific tasks through function calls.
  • Creating automated question answering systems capable of retrieving information from various data sources.
  • Developing advanced natural language processing applications such as text summarization, machine translation, and text generation.
  • Building agents: Creating intelligent agents capable of interacting with the environment and performing actions based on language.
  • Multi-agent systems: Developing multi-agent systems where agents can communicate and collaborate to solve complex problems.

How to Use

1. Install necessary libraries:

! pip install transformers torch

2. Initialize the tokenizer and model:

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import json

# Initialize the tokenizer and model
tokenizer = AutoTokenizer.from_pretrained("ricepaper/vi-gemma-2-2b-function-calling")
model = AutoModelForCausalLM.from_pretrained(
    "ricepaper/vi-gemma-2-2b-function-calling",
    device_map="auto",
    torch_dtype=torch.float16,
)

3. Build a function to process user queries:

def process_user_query(user_query, messages, available_tools):
    """
    Processes user queries, generates responses, checks for, and executes function calls (if any).

    Args:
        user_query (str): The query from the user.
        messages (list): The list of current messages in the conversation.
        available_tools (dict): A dictionary containing available functions.

    Returns:
        str: The final response after processing function calls (if any).
    """

    # Add the user query to the messages
    messages.append({"role": "user", "content": user_query})

    # Generate a response from the model
    input_ids = tokenizer.apply_chat_template(
        messages,
        add_generation_prompt=True,
        return_tensors="pt"
    ).to(model.device)
    outputs = model.generate(
        input_ids,
        max_new_tokens=300,
        # ... (Other generate parameters)
    )
    response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)

    try:
        # Convert the JSON string to a Python list
        response_list = json.loads(response)
        # Add the response to messages if there's a function call
        messages.append({"role": "assistant", "content": response})
    except json.JSONDecodeError:
        # If the response is not JSON, assume no function call
        response_list = []

    # Initialize a list to store function responses
    function_responses = []

    # Iterate through each element in the list
    for response_dict in response_list:
        if "name" in response_dict and "arguments" in response_dict:
            function_name = response_dict.get("name")
            function_args = response_dict.get("arguments")

            if function_name in available_tools:
                # Execute the function call
                print(f"Calling function {function_name} with arguments {function_args}\n")
                function_to_call = available_tools[function_name]
                function_response = function_to_call(**function_args)
                
                # Store the result as a dictionary
                function_responses.append({
                    "name": function_name,
                    "response": function_response
                })
            else:
                print(f"Function {function_name} not found")

    # Add the list of function responses to the messages
    if function_responses:
        messages.append({
            "role": "user",
            "content": f"FUNCTION RESPONSES:\n{json.dumps(function_responses, ensure_ascii=False)}"
        })
        print(messages[-1].get("content"))

        # Generate a new response after processing function calls
        input_ids = tokenizer.apply_chat_template(
            messages,
            add_generation_prompt=True,
            return_tensors="pt"
        ).to(model.device)
        outputs = model.generate(
            input_ids,
            max_new_tokens=300,
            # ... (Other generate parameters)
        )
        response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)

    return response

4. Create helper functions and declare the tools list:

## Function simulating tip calculation for a bill
def calculate_tip(bill_amount: float, tip_percentage: float) -> str:
  """Calculates the tip amount for a bill and returns a string describing the result.

  Args:
    bill_amount: The total amount of the bill.
    tip_percentage: The tip percentage.

  Returns:
    A string describing the tip amount and the total amount to be paid.
  """

  tip_amount = bill_amount * (tip_percentage / 100)
  total_amount = bill_amount + tip_amount
  return f"The tip amount is: {tip_amount:.2f}\nThe total amount to be paid is: {total_amount:.2f}"

# Declare the tools list
tools = """
{
  "name": "calculate_tip",
  "description": "Calculate the tip amount for a bill",
  "parameters": {
    "type": "object",
    "properties": {
      "bill_amount": {
        "type": "number",
        "description": "The total bill amount"
      },
      "tip_percentage": {
        "type": "number",
        "description": "The tip percentage"
      }
    },
    "required": [
      "bill_amount",
      "tip_percentage"
    ]
  }
},
"""

# Create a dictionary mapping function names to their corresponding functions
available_tools = {
    "calculate_tip": calculate_tip,
}

5. Create a new conversation history and use the model:

# Create a new conversation history
messages = [
    {"role": "user", "content": f"""You are a helpful assistant with access to the following functions. Use them if necessary {tools}"""},
    {"role": "assistant", "content": "Hello, how can I assist you?"},
]
# Use the model
res = 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)
messages.append({"role": "assistant", "content": res})
print("\n"+res)
# Calling function calculate_tip with arguments {'bill_amount': 50, 'tip_percentage': 15}

# FUNCTION RESPONSES:
# [{"name": "calculate_tip", "response": "The tip amount is: 7.50\nThe total amount to be paid is: 57.50"}]

# The tip amount for your bill is $7.50. The total amount to be paid is $57.50.

messages
# [{'role': 'user',
#   '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'},
#  {'role': 'assistant', 'content': 'Hello, how can I assist you?'},
#  {'role': 'user',
#   'content': 'I need help calculating the tip for my bill. The total is $50 and I would like to leave a 15% tip.'},
#  {'role': 'assistant',
#   'content': '[{"name": "calculate_tip", "arguments": {"bill_amount": 50, "tip_percentage": 15}}]'},
#  {'role': 'user',
#   'content': 'FUNCTION RESPONSES:\n[{"name": "calculate_tip", "response": "The tip amount is: 7.50\\nThe total amount to be paid is: 57.50"}]'},
#  {'role': 'assistant',
#   'content': 'The tip amount for your bill is $7.50. The total amount to be paid is $57.50.'}]

Uploaded model

This gemma model was trained 2x faster with Unsloth and Huggingface's TRL library.

Downloads last month
106
Safetensors
Model size
2.61B params
Tensor type
FP16
·
Inference Examples
Inference API (serverless) is not available, repository is disabled.

Model tree for ricepaper/vi-gemma-2-2b-function-calling

Finetuned
this model

Collection including ricepaper/vi-gemma-2-2b-function-calling