Views
No views yet
1import json
2import torch
3from transformers import AutoModelForCausalLM, AutoTokenizer
4
5device = "cuda" # or "cpu"
6model_path = "ibm-granite/granite-20b-functioncalling"
7tokenizer = AutoTokenizer.from_pretrained(model_path)
8# drop device_map if running on CPU
9model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device)
10model.eval()
11
12# define the user query and list of available functions
13query = "What's the current weather in New York?"
14functions = [
15 {
16 "name": "get_current_weather",
17 "description": "Get the current weather",
18 "parameters": {
19 "type": "object",
20 "properties": {
21 "location": {
22 "type": "string",
23 "description": "The city and state, e.g. San Francisco, CA"
24 }
25 },
26 "required": ["location"]
27 }
28 },
29 {
30 "name": "get_stock_price",
31 "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.",
32 "parameters": {
33 "type": "object",
34 "properties": {
35 "ticker": {
36 "type": "string",
37 "description": "The stock ticker symbol, e.g. AAPL for Apple Inc."
38 }
39 },
40 "required": ["ticker"]
41 }
42 }
43]
44
45
46# serialize functions and define a payload to generate the input template
47payload = {
48 "functions_str": [json.dumps(x) for x in functions],
49 "query": query,
50}
51
52instruction = tokenizer.apply_chat_template(payload, tokenize=False, add_generation_prompt=True)
53
54# tokenize the text
55input_tokens = tokenizer(instruction, return_tensors="pt").to(device)
56
57# generate output tokens
58outputs = model.generate(**input_tokens, max_new_tokens=100)
59
60# decode output tokens into text
61outputs = tokenizer.batch_decode(outputs)
62
63# loop over the batch to print, in this example the batch size is 1
64for output in outputs:
65 # Each function call in the output will be preceded by the token "<function_call>" followed by a
66 # json serialized function call of the format {"name": $function_name$, "arguments" {$arg_name$: $arg_val$}}
67 # In this specific case, the output will be: <function_call> {"name": "get_current_weather", "arguments": {"location": "New York"}}
68 print(output)