Views
No views yet
transformers>=4.37.0.1import json
2import torch
3from transformers import AutoModelForCausalLM, AutoTokenizer
4
5model_name = "MadeAgents/Hammer2.0-3b"
6model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype="auto", trust_remote_code=True)
7tokenizer = AutoTokenizer.from_pretrained(model_name)
8
9# Please use our provided instruction prompt for best performance
10TASK_INSTRUCTION = """You are a tool calling assistant. In order to complete the user's request, you need to select one or more appropriate tools from the following tools and fill in the correct values for the tool parameters. Your specific tasks are:
111. Make one or more function/tool calls to meet the request based on the question.
122. If none of the function can be used, point it out and refuse to answer.
133. If the given question lacks the parameters required by the function, also point it out.
14"""
15
16FORMAT_INSTRUCTION = """
17The output MUST strictly adhere to the following JSON format, and NO other text MUST be included.
18The example format is as follows. Please make sure the parameter type is correct. If no function call is needed, please directly output an empty list '[]'
19```
20[
21 {"name": "func_name1", "arguments": {"argument1": "value1", "argument2": "value2"}},
22 ... (more tool calls as required)
23]
24```
25"""
26
27# Define the input query and available tools
28query = "Where can I find live giveaways for beta access and games? And what's the weather like in New York, US?"
29
30live_giveaways_by_type = {
31 "name": "live_giveaways_by_type",
32 "description": "Retrieve live giveaways from the GamerPower API based on the specified type.",
33 "parameters": {
34 "type": "object",
35 "properties": {
36 "type": {
37 "type": "string",
38 "description": "The type of giveaways to retrieve (e.g., game, loot, beta).",
39 "default": "game"
40 }
41 },
42 "required": ["type"]
43 }
44}
45get_current_weather={
46 "name": "get_current_weather",
47 "description": "Get the current weather",
48 "parameters": {
49 "type": "object",
50 "properties": {
51 "location": {
52 "type": "string",
53 "description": "The city and state, e.g. San Francisco, CA"
54 }
55 },
56 "required": ["location"]
57 }
58 }
59get_stock_price={
60 "name": "get_stock_price",
61 "description": "Retrieves the current stock price for a given ticker symbol. The ticker symbol must be a valid symbol for a publicly traded company on a major US stock exchange like NYSE or NASDAQ. The tool will return the latest trade price in USD. It should be used when the user asks about the current or most recent price of a specific stock. It will not provide any other information about the stock or company.",
62 "parameters": {
63 "type": "object",
64 "properties": {
65 "ticker": {
66 "type": "string",
67 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
68 }
69 },
70 "required": ["ticker"]
71 }
72 }
73
74def convert_to_format_tool(tools):
75 ''''''
76 if isinstance(tools, dict):
77 format_tools = {
78 "name": tools["name"],
79 "description": tools["description"],
80 "parameters": tools["parameters"].get("properties", {}),
81 }
82 required = tools["parameters"].get("required", [])
83 for param in required:
84 format_tools["parameters"][param]["required"] = True
85 for param in format_tools["parameters"].keys():
86 if "default" in format_tools["parameters"][param]:
87 default = format_tools["parameters"][param]["default"]
88 format_tools["parameters"][param]["description"]+=f"default is \'{default}\'"
89 return format_tools
90 elif isinstance(tools, list):
91 return [convert_to_format_tool(tool) for tool in tools]
92 else:
93 return tools
94# Helper function to build the input prompt for our model
95def build_prompt(task_instruction: str, format_instruction: str, tools: list, query: str):
96 prompt = f"[BEGIN OF TASK INSTRUCTION]\n{task_instruction}\n[END OF TASK INSTRUCTION]\n\n"
97 prompt += f"[BEGIN OF AVAILABLE TOOLS]\n{json.dumps(tools)}\n[END OF AVAILABLE TOOLS]\n\n"
98 prompt += f"[BEGIN OF FORMAT INSTRUCTION]\n{format_instruction}\n[END OF FORMAT INSTRUCTION]\n\n"
99 prompt += f"[BEGIN OF QUERY]\n{query}\n[END OF QUERY]\n\n"
100 return prompt
101
102# Build the input and start the inference
103openai_format_tools = [live_giveaways_by_type, get_current_weather,get_stock_price]
104format_tools = convert_to_format_tool(openai_format_tools)
105content = build_prompt(TASK_INSTRUCTION, FORMAT_INSTRUCTION, format_tools, query)
106
107messages=[
108 { 'role': 'user', 'content': content}
109]
110inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
111
112# tokenizer.eos_token_id is the id of <|EOT|> token
113outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
114print(tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True))