Views
No views yet
Note: The template supports multiple tools but the model is fine-tuned on a dataset consisting of examples with a single tool.
1chat_template = (
2 "{% for message in messages %}"
3 "{% if loop.first and messages[0]['role'] != 'system' %}"
4 "{% if tools %}"
5 "<|im_start|>system\nYou are a helpful assistant with access to the following tools. Use them if required - \n"
6 "```json\n{{ tools | tojson }}\n```<|im_end|>\n"
7 "{% else %}"
8 "<|im_start|>system\nYou are a helpful assistant.\n<|im_end|>\n"
9 "{% endif %}"
10 "{% endif %}"
11 "{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}"
12 "{% endfor %}"
13 "{% if add_generation_prompt %}"
14 "{{ '<|im_start|>assistant\n' }}"
15 "{% endif %}"
16)1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer
3
4model_id = "Qwen2-1.5B-Instruct-Function-Calling-v1"
5model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32, device_map="auto")
6tokenizer = AutoTokenizer.from_pretrained(model_id)
7
8def inference(prompt: str) -> str:
9 model_inputs = tokenizer([prompt], return_tensors="pt").to('cuda')
10 generated_ids = model.generate(model_inputs.input_ids, max_new_tokens=512)
11 generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
12 response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
13 return response
14
15messages = [{"role": "user", "content": "What is the speed of light?"}]
16prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
17response = inference(prompt)
18print(response)1import json
2from typing import List, Dict
3
4def get_prompt(user_input: str, tools: List[Dict] | None = None):
5 prompt = 'Extract the information from the following - \n{}'.format(user_input)
6 messages = [{"role": "user", "content": prompt}]
7 prompt = tokenizer.apply_chat_template(
8 messages,
9 tokenize=False,
10 add_generation_prompt=True,
11 tools=tools
12 )
13 return prompt
14
15tool = {
16 "type": "function",
17 "function": {
18 "name": "get_company_info",
19 "description": "Correctly extracted company information with all the required parameters with correct types",
20 "parameters": {
21 "properties": {
22 "name": {"title": "Name", "type": "string"},
23 "investors": {
24 "items": {"type": "string"},
25 "title": "Investors",
26 "type": "array"
27 },
28 "valuation": {"title": "Valuation", "type": "string"},
29 "source": {"title": "Source", "type": "string"}
30 },
31 "required": ["investors", "name", "source", "valuation"],
32 "type": "object"
33 }
34 }
35}
36input_text = "Founded in 2021, Pluto raised $4 million across multiple seed funding rounds, valuing the company at $12 million (pre-money), according to PitchBook. The startup was backed by investors including Switch Ventures, Caffeinated Capital and Maxime Seguineau."
37prompt = get_prompt(input_text, tools=[tool])
38response = inference(prompt)
39print(response)
40# ```json
41# {
42# "name": "get_company_info",
43# "arguments": {
44# "name": "Pluto",
45# "investors": [
46# "Switch Ventures",
47# "Caffeinated Capital",
48# "Maxime Seguineau"
49# ],
50# "valuation": "$12 million",
51# "source": "PitchBook"
52# }
53# }
54# ```1import re
2from enum import Enum
3
4from pydantic import BaseModel, Field # pip install pydantic
5from instructor.function_calls import openai_schema # pip install instructor
6
7# Define functions using pydantic classes
8class PaperCategory(str, Enum):
9 TYPE_1_DIABETES = 'Type 1 Diabetes'
10 TYPE_2_DIABETES = 'Type 2 Diabetes'
11
12class Classification(BaseModel):
13 label: PaperCategory = Field(..., description='Provide the most likely category')
14 reason: str = Field(..., description='Give a detailed explanation with quotes from the abstract explaining why the paper is related to the chosen label.')
15
16function_definition = openai_schema(Classification).openai_schema
17tool = dict(type='function', function=function_definition)
18input_text = "1,25-dihydroxyvitamin D(3) (1,25(OH)(2)D(3)), the biologically active form of vitamin D, is widely recognized as a modulator of the immune system as well as a regulator of mineral metabolism. The objective of this study was to determine the effects of vitamin D status and treatment with 1,25(OH)(2)D(3) on diabetes onset in non-obese diabetic (NOD) mice, a murine model of human type I diabetes. We have found that vitamin D-deficiency increases the incidence of diabetes in female mice from 46% (n=13) to 88% (n=8) and from 0% (n=10) to 44% (n=9) in male mice as of 200 days of age when compared to vitamin D-sufficient animals. Addition of 50 ng of 1,25(OH)(2)D(3)/day to the diet prevented disease onset as of 200 days and caused a significant rise in serum calcium levels, regardless of gender or vitamin D status. Our results indicate that vitamin D status is a determining factor of disease susceptibility and oral administration of 1,25(OH)(2)D(3) prevents diabetes onset in NOD mice through 200 days of age."
19prompt = get_prompt(input_text, tools=[tool])
20output = inference(prompt)
21print(output)
22# ```json
23# {
24# "name": "Classification",
25# "arguments": {
26# "label": "Type 1 Diabetes",
27# "reason": "The study investigated the effect of vitamin D status and treatment with 1,25(OH)(2)D(3) on diabetes onset in non-obese diabetic (NOD) mice. It also concluded that vitamin D deficiency leads to an increase in diabetes incidence and that the addition of 1,25(OH)(2)D(3) can prevent diabetes onset in NOD mice."
28# }
29# }
30# ```
31# Extract JSON string using regex
32output = re.search(r'```json\s*(\{.*?\})\s*```', output).group(1)
33output = Classification(**json.loads(_output)['arguments'])
34print(output)
35# Classification(label=<PaperCategory.TYPE_1_DIABETES: 'Type 1 Diabetes'>, reason='The study investigated the effect of vitamin D status and treatment with 1,25(OH)(2)D(3) on diabetes onset in non-obese diabetic (NOD) mice. It also concluded that vitamin D deficiency leads to an increase in diabetes incidence and that the addition of 1,25(OH)(2)D(3) can prevent diabetes onset in NOD mice.')| Training Loss | Epoch | Step | Validation Loss |
|---|---|---|---|
| 0.4004 | 0.0101 | 20 | 0.4852 |
| 0.3624 | 0.0201 | 40 | 0.3221 |
| 0.2855 | 0.0302 | 60 | 0.2818 |
| 0.2652 | 0.0402 | 80 | 0.2592 |
| 0.2214 | 0.0503 | 100 | 0.2463 |
| 0.2471 | 0.0603 | 120 | 0.2358 |
| 0.2122 | 0.0704 | 140 | 0.2310 |
| 0.2048 | 0.0804 | 160 | 0.2275 |
| 0.2406 | 0.0905 | 180 | 0.2251 |
| 0.2445 | 0.1006 | 200 | 0.2248 |
1peft==0.11.1
2transformers==4.42.3
3torch==2.3.1+cu121
4datasets==2.20.0
5tokenizers==0.19.1