├── LICENSE ├── README.md ├── grammar-based-generation ├── SeqSNIPS_SeqATIS-data-gen.py └── SeqTopV2-data-gen.py ├── llm-based-generation └── llm-data-gen.py └── requirements.txt /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # API-BLEND 2 | **A Comprehensive Corpora for Training and Benchmarking API LLMs.** 3 | 4 | Paper Link: https://arxiv.org/abs/2402.15491 5 | 6 | 7 | API-BLEND is a collection of 10 datasets for training and systematic testing of tool-augmented LLMs. The datasets mimic real-world scenarios involving API-tasks such as API / tool detection, slot filling, and sequencing of the detected APIs. Out of 10 datasets we have curated 6 datasets from the existing datasets, and the other 4, we have used them off-the-shelf (for OOD tests). 8 | 9 | **Note:** Currently, we are in the process of obtaining license clearance to release the curated datasets directly. So, for the time, we have outlined the steps involved in curating them from the raw datasets. 10 | ## Install Dependencies 11 | 12 | ```commandline 13 | conda create --name api-blend python=3.9 14 | conda activate api-blend 15 | pip install -r requirements.txt 16 | python -m spacy download en_core_web_sm 17 | ``` 18 | 19 | For LLM-based data-generation we have used [IBM Generative AI Python SDK](https://pypi.org/project/ibm-generative-ai/). Please follow the instructions to generate unique API key to access IBM Generative AI. 20 | ```commandline 21 | pip install --upgrade ibm-generative-ai==2.2.0 22 | ``` 23 | 24 | ## Datasets Curation 25 | ### 1. LLM-based Data Generation 26 | - ##### Raw Data: 27 | We have curated SeqSGD (from SGD) and SeqMultiWOZ (from MultiWOZ) using LLM. Please download the raw data from the following links. 28 | 29 | - SGD: [Link](https://github.com/google-research-datasets/dstc8-schema-guided-dialogue) 30 | - MultiWOZ: [Link](https://github.com/budzianowski/multiwoz/tree/master/data/MultiWOZ_2.2) 31 | 32 | - ##### Generate Data: 33 | Here is an example to generate SeqMultiWOZ, where `data/raw/MultiWOZ_2.2` is the raw data dir. Same codebase works for SeqSGD. 34 | ```commandline 35 | export GENAI_API= 36 | export GENAI_KEY= 37 | 38 | python llm-based-generation/llm-data-gen.py \ 39 | --data_dir data/raw/MultiWOZ_2.2 \ 40 | --save_dir data/processed/SeqMultiWOZ \ 41 | --dataset_name multiwoz \ 42 | --model google/flan-t5-xxl 43 | ``` 44 | 45 | ### 2. Grammar-based Data Generation 46 | - ##### Raw Data: 47 | Using grammar based generation, we have generated 4 datasets. Please download the raw datasets from the following links 48 | - ATIS: [Link](https://www.kaggle.com/datasets/hassanamin/atis-airlinetravelinformationsystem) 49 | - SNIPS: [Link](https://github.com/sonos/nlu-benchmark) 50 | - TopV2: [Link](https://fb.me/TOPv2Dataset) 51 | - ToolQA: [Link](https://github.com/night-chen/ToolQA) 52 | 53 | - ##### Generate Data: 54 | 55 | - **SeqATIS and SeqSNIPS**: 56 | Please download the SNIPS and ATIS datasets from the above link. Run the below script to generate SeqSNIPS and SeqATIS datasets, where `data/raw/` contains the raw `SNIPS` and `ATIS` datasets. 57 | ```commandline 58 | python grammar-based-generation/SeqSNIPS_SeqATIS-data-gen.py \ 59 | --data_dir data/raw/ \ 60 | --save_dir data/processed/ 61 | ``` 62 | - **SeqTopV2**: 63 | Please download the TopV2 following the above link. Run the below script to generate SeqTopV2 dataset, where `data/raw/TOPv2_Dataset` is the raw data. 64 | 65 | ```commandline 66 | python grammar-based-generation/SeqTopV2-data-gen.py \ 67 | --data_dir data/raw/TOPv2_Dataset \ 68 | --save_dir data/processed/SeqTopV2 69 | ``` 70 | - **SeqToolQA**: The original dataset of ToolQA does not contain the APIs, it only comes with a question and a final answer. So, we have used their data-generation [code](https://github.com/night-chen/ToolQA) for each template to generate the intermediate APIs, which are of utmost importance to us. Here is an example, where the `apis` key is generated by us following their codebase. 71 | ``` 72 | { 73 | "qid": "easy-flight-0034", 74 | "input": "How long was the different between the CRS recorded departure time and actual departure time of the AA529 flight from LAX to MIA on 2022-05-03?", 75 | "apis": [ 76 | "LoadDB[flights]", 77 | "FilterDB[Origin=LAX, Dest=MIA, Flight_Number_Marketing_Airline=529, IATA_Code_Marketing_Airline=AA]", 78 | "GetValue[DepTime]", 79 | "GetValue[CRSDepTime]", 80 | "PythonInterpreter(abs(DepTime - CRSDepTime))" 81 | ], 82 | "output": "45" 83 | } 84 | ``` 85 | -------------------------------------------------------------------------------- /grammar-based-generation/SeqSNIPS_SeqATIS-data-gen.py: -------------------------------------------------------------------------------- 1 | import os, json, re 2 | from tqdm import tqdm 3 | import argparse 4 | import spacy 5 | en = spacy.load('en_core_web_sm') 6 | 7 | 8 | def read_file(file_path): 9 | """ Read data file of given path. 10 | :param file_path: path of data file. 11 | :return: list of sentence, list of slot and list of intent. 12 | """ 13 | texts, slots, intents = [], [], [] 14 | text, slot = [], [] 15 | with open(file_path, 'r', encoding="utf8") as fr: 16 | for line in fr.readlines(): 17 | items = line.strip().split() 18 | if len(items) == 1: 19 | texts.append(text) 20 | slots.append(slot) 21 | if "/" not in items[0]: 22 | intents.append(items) 23 | else: 24 | new = items[0].split("/") 25 | intents.append([new[1]]) 26 | # clear buffer lists. 27 | text, slot = [], [] 28 | elif len(items) == 2: 29 | text.append(items[0].strip()) 30 | slot.append(items[1].strip()) 31 | return texts, slots, intents 32 | 33 | 34 | def split_string_on_delimiters(string, delimiters, max_splits=None): 35 | # Create a pattern for all delimiters 36 | pattern = '|'.join(map(re.escape, delimiters)) 37 | 38 | # Split the string using the pattern and max_splits 39 | return re.split(pattern, string, maxsplit=max_splits) 40 | 41 | 42 | def clause_parse(text): 43 | doc = en(text) 44 | seen = set() 45 | chunks = [] 46 | for sent in doc.sents: 47 | heads = [cc for cc in sent.root.children if cc.dep_ == 'conj'] 48 | 49 | for head in heads: 50 | words = [ww for ww in head.subtree] 51 | for word in words: 52 | seen.add(word) 53 | chunk = (' '.join([ww.text for ww in words])) 54 | chunks.append((head.i, chunk)) 55 | 56 | unseen = [ww for ww in sent if ww not in seen] 57 | chunk = ' '.join([ww.text for ww in unseen]) 58 | chunks.append((sent.root.i, chunk)) 59 | 60 | chunks = sorted(chunks, key=lambda x: x[0]) 61 | return chunks 62 | 63 | 64 | def parse_IOB(tokens, tags): 65 | from nltk import pos_tag 66 | from nltk.tree import Tree 67 | from nltk.chunk import conlltags2tree 68 | # tag each token with pos 69 | pos_tags = [pos for token, pos in pos_tag(tokens)] #nltk.download('averaged_perceptron_tagger') 70 | # convert the BIO / IOB tags to tree 71 | conlltags = [(token, pos, tg) for token, pos, tg in zip(tokens, pos_tags, tags)] 72 | ne_tree = conlltags2tree(conlltags) # parse the tree to get our original text 73 | original_text = [] 74 | for subtree in ne_tree: 75 | # checking for 'O' tags 76 | if type(subtree) == Tree: 77 | original_label = subtree.label() 78 | original_string = " ".join([token for token, pos in subtree.leaves()]) 79 | original_text.append((original_string, original_label)) 80 | return original_text 81 | 82 | 83 | def create_dataset(data_dir, save_dir): 84 | for dataset in ['ATIS', 'SNIPS']: 85 | print(dataset) 86 | num_failed_exs = 0 87 | for split in ['train.txt', 'dev.txt', 'test.txt']: 88 | print(split) 89 | fpath = data_dir + f'/{dataset}/{split}' 90 | raw_data = [] 91 | texts, slots, intents = read_file(fpath) 92 | for idx in tqdm(range(len(texts))): 93 | sentence = ' '.join(texts[idx]).strip() 94 | all_intents = intents[idx][0].split('#') 95 | if len(all_intents) == 1: 96 | clauses = [sentence] 97 | else: 98 | clauses = split_string_on_delimiters(sentence, ['and also', 'and then', ',', 'and', 'also'], max_splits=len(all_intents)) 99 | if len(clauses) != len(all_intents): 100 | clauses = split_string_on_delimiters(sentence, [',', 'and then'], max_splits=len(all_intents)) 101 | if len(clauses) != len(all_intents): 102 | if len(clauses) != len(all_intents): 103 | clauses = clause_parse(sentence) 104 | if len(clauses) != len(all_intents): 105 | new_clauses = [] 106 | for idx, c in enumerate(clauses): 107 | id, clause = c 108 | if len(new_clauses) == 0: 109 | new_clauses.append(clause) 110 | elif new_clauses[-1].strip().endswith('and and'): 111 | new_clauses[-1] = new_clauses[-1].replace('and and', 'and').strip() + ' '+ clause 112 | else: 113 | new_clauses.append(clause) 114 | clauses = new_clauses 115 | if len(clauses) > len(all_intents): 116 | new_clauses = [] 117 | for c in clauses: 118 | if len(new_clauses) > 0: 119 | if len(new_clauses[-1].split(' ')) < 3: 120 | new_clauses[-1] += ' '+ c 121 | continue 122 | elif len(c.split(' ')) < 5: 123 | new_clauses[-1] += ' ' + c 124 | continue 125 | new_clauses.append(c) 126 | clauses = new_clauses 127 | start = 0 128 | apis = [] 129 | for i in range(len(clauses)): 130 | if type(clauses[i]) == tuple: 131 | num, clause = clauses[i] 132 | else: 133 | clause = clauses[i] 134 | num_words = len(clause.split(' ')) 135 | slots_arr = slots[idx][start:start+num_words] 136 | tokens = texts[idx][start:start+num_words] 137 | params = parse_IOB(tokens, slots_arr) 138 | start += num_words 139 | params_dic = {} 140 | for (val, name) in params: 141 | if name not in params_dic: 142 | params_dic[name] = [] 143 | params_dic[name].append(val) 144 | apis.append( 145 | { 146 | 'API': all_intents[i], 147 | 'Parameters': params_dic 148 | } 149 | ) 150 | raw_data.append({ 151 | 'text': sentence, 152 | 'APIs': apis, 153 | }) 154 | directory = f"{save_dir}/Seq{dataset}" 155 | if not os.path.exists(directory): 156 | os.makedirs(directory) 157 | out_fname = f"{directory}/{split.replace('.txt', '')}.json" 158 | with open(out_fname, 'w') as file: 159 | json.dump(raw_data, file, indent=4) 160 | print('Number of examples: ', len(raw_data)) 161 | print('num_failed_exs: ', num_failed_exs) 162 | print('*'*20) 163 | print('-'*50) 164 | 165 | 166 | if __name__ == '__main__': 167 | parser = argparse.ArgumentParser() 168 | parser.add_argument("--data_dir", type=str) 169 | parser.add_argument("--save_dir", type=str) 170 | args = parser.parse_args() 171 | os.makedirs(args.save_dir, exist_ok=True) 172 | create_dataset(args.data_dir, args.save_dir) -------------------------------------------------------------------------------- /grammar-based-generation/SeqTopV2-data-gen.py: -------------------------------------------------------------------------------- 1 | import json 2 | import csv 3 | import re 4 | import argparse 5 | import os 6 | 7 | 8 | def get_ontologies(parsed_string): 9 | ontologies = {} 10 | text = re.sub(r"\s*\[\s*", " [ ", parsed_string) 11 | text = re.sub(r"\s*\]\s*", " ] ", text) 12 | left_sq_brackets = [] 13 | intents = [] 14 | for token in text.strip().split(): 15 | if token == "[": 16 | if len(left_sq_brackets) > 0: 17 | left_sq_brackets[-1] += 1 18 | elif token == "]": 19 | left_sq_brackets[-1] -= 1 20 | if left_sq_brackets[-1] == 0: 21 | left_sq_brackets.pop() 22 | intents.pop() 23 | elif token.startswith("IN:"): 24 | if len(left_sq_brackets) > 0: 25 | left_sq_brackets[-1] -= 1 26 | left_sq_brackets.append(1) 27 | intent = token[len("IN:"):] 28 | intents.append(intent) 29 | ontologies[intent] = ontologies[intent] if intent in ontologies else [] 30 | elif token.startswith("SL:"): 31 | slot = token[len("SL:"):] 32 | if slot not in ontologies[intents[-1]]: 33 | ontologies[intents[-1]].append(slot) 34 | return ontologies 35 | 36 | 37 | def parse_string_to_tree(input_string): 38 | tokens = input_string.split() 39 | stack = [] 40 | for token in tokens: 41 | if token.startswith('['): 42 | intent = token[1:].split(':')[1] 43 | node = {'intent': intent, 'slots': []} 44 | if stack: 45 | stack[-1]['slots'].append(node) 46 | stack.append(node) 47 | elif token.startswith('SL:'): 48 | slot = token[3:] 49 | if stack: 50 | stack[-1]['slots'].append(slot) 51 | elif token == ']': 52 | if len(stack) > 1: 53 | top = stack.pop() 54 | if len(stack) > 0: 55 | stack[-1]['slots'].append(top) 56 | return stack[0] 57 | 58 | 59 | def extract_nested_slots(input_string): 60 | matches = [] 61 | while True: 62 | match = re.search(r'\[SL:([^][]+)\s+([^][]+)\]', input_string) 63 | if match: 64 | slot_name = match.group(1) 65 | slot_text = match.group(2) 66 | matches.append((slot_name, slot_text.strip())) 67 | input_string = input_string[:match.start()] + input_string[match.end():] 68 | else: 69 | break 70 | return matches 71 | 72 | 73 | def extract_slots(input_string): 74 | matches = [] 75 | stack = [] 76 | for i, char in enumerate(input_string): 77 | if char == '[': 78 | stack.append(i) 79 | elif char == ']': 80 | if stack: 81 | start = stack.pop() 82 | if input_string[start:start + 4] == '[SL:': 83 | slot_info = input_string[start:i + 1] 84 | matches.append(slot_info) 85 | 86 | return matches 87 | 88 | def curate_seqtopv2(data_dir, save_dir): 89 | num_intents_total = {"1": 0, "2": 0, "3": 0, '4': 0, '5': 0} 90 | api_catalog = {} 91 | num_intents_train = {"1": 0, "2": 0, "3": 0, '4': 0, '5': 0} 92 | num_intents_eval = {"1": 0, "2": 0, "3": 0, '4': 0, '5': 0} 93 | num_intents_test = {"1": 0, "2": 0, "3": 0, '4': 0, '5': 0} 94 | for domain in ['navigation', 'alarm', 'event', 'messaging', 'music', 'reminder', 'timer', 'weather']: 95 | for split in ['train', 'eval', 'test']: 96 | json_data = [] 97 | num_intents = {"1": 0, "2": 0, "3": 0, '4': 0, '5': 0} 98 | tsv_file_path = os.path.join(data_dir, f'{domain}_{split}.tsv') 99 | # Open and read the TSV file 100 | with open(tsv_file_path, "r", newline="") as file: 101 | # Create a CSV reader with tab as the delimiter 102 | reader = csv.reader(file, delimiter="\t") 103 | 104 | # Iterate through each row in the TSV file 105 | for idx, row in enumerate(reader): 106 | if idx == 0: 107 | continue 108 | question = row[1] 109 | input_string = row[2] 110 | utterance_ontologies = get_ontologies(input_string) 111 | ontologies = {} 112 | ontologies = { 113 | key: list( 114 | set( 115 | ontologies.get(key, []) 116 | + utterance_ontologies.get(key, []) 117 | ) 118 | ) 119 | for key in (ontologies.keys() | utterance_ontologies.keys()) 120 | } 121 | 122 | matches_2 = extract_slots(input_string) 123 | # Print the extracted slot information 124 | slot_info = {} 125 | for match in matches_2: 126 | parts = match.split(' ', maxsplit=1) 127 | slot_name = parts[0].replace('[', '').strip() 128 | slot_text = parts[1].replace(']', '').strip() 129 | if '[IN:' in slot_text: 130 | pattern_intent = r'\[IN:([^]][^\s]*)' 131 | matches_intent = re.findall(pattern_intent, slot_text) 132 | for in_match in matches_intent: 133 | slot_text = in_match 134 | break 135 | if slot_name in slot_info: 136 | slot_info[slot_name].append(slot_text) 137 | else: 138 | slot_info[slot_name] = [slot_text] 139 | apis_seq = [] 140 | 141 | for intent, slots in ontologies.items(): 142 | if 'UNSUPPORTED_' in intent: 143 | continue 144 | api_slots = {} 145 | for slot in slots: 146 | slt_val = slot_info['SL:' + slot][0] 147 | slot_info['SL:' + slot] = slot_info['SL:' + slot][1:] 148 | api_slots[slot] = slt_val 149 | api_slots_arr = [f'{slot} = "{val}"' for slot, val in api_slots.items()] 150 | api = f'{intent}({", ".join(api_slots_arr)})' 151 | apis_seq.append((api, input_string.index('IN:' + intent))) 152 | if intent not in api_catalog: 153 | api_catalog[intent] = { 154 | "description": "", 155 | "parameters": [] 156 | } 157 | else: 158 | for slot_name, val in api_slots.items(): 159 | if slot_name not in api_catalog[intent]["parameters"]: 160 | api_catalog[intent]["parameters"].append(slot_name) 161 | 162 | # Use re.search to find the pattern in the input string 163 | if len(apis_seq) > 0: 164 | ordered_seq = sorted(apis_seq, key=lambda tup: tup[1], reverse=True) 165 | only_apis = [] 166 | for api in ordered_seq: 167 | only_apis.append(api[0]) 168 | json_data.append( 169 | { 170 | "input": question, 171 | 'apis': only_apis, 172 | } 173 | ) 174 | num_intents[str(len(only_apis))] += 1 175 | num_intents_total[str(len(only_apis))] += 1 176 | save_path = os.path.join(save_dir, f"{domain}_{split}.json") 177 | with open(save_path, 'w+') as file: 178 | json.dump(json_data, file, indent=4) 179 | 180 | print(tsv_file_path) 181 | print('Num of examples: ', len(json_data)) 182 | for key, val in num_intents.items(): 183 | print(f'\tNumber of examples with {key} APIs: {val}') 184 | print('-' * 20) 185 | if split == 'train': 186 | for key, val in num_intents.items(): 187 | num_intents_train[key] += val 188 | elif split == 'eval': 189 | for key, val in num_intents.items(): 190 | num_intents_eval[key] += val 191 | elif split == 'test': 192 | for key, val in num_intents.items(): 193 | num_intents_test[key] += val 194 | print('Overall stats: ') 195 | print(num_intents_total) 196 | for key, val in num_intents_total.items(): 197 | print(f'Number of examples with {key} APIs: {val}') 198 | with open(os.path.join(save_dir, 'api_spec.json'), 'w+') as file: 199 | json.dump(api_catalog, file, indent=4) 200 | 201 | print('TRAIN:') 202 | num_train = 0 203 | for key, val in num_intents_train.items(): 204 | print(f'Number of examples with {key} APIs: {val}') 205 | num_train += val 206 | print('EVAL:') 207 | num_eval = 0 208 | for key, val in num_intents_eval.items(): 209 | print(f'Number of examples with {key} APIs: {val}') 210 | num_eval += val 211 | print('TEST:') 212 | num_test = 0 213 | for key, val in num_intents_test.items(): 214 | print(f'Number of examples with {key} APIs: {val}') 215 | num_test += val 216 | 217 | print('num_train: ', num_train) 218 | print('num_eval: ', num_eval) 219 | print('num_test: ', num_test) 220 | print('total: ', str(num_train + num_eval + num_test)) 221 | 222 | 223 | if __name__ == '__main__': 224 | parser = argparse.ArgumentParser() 225 | parser.add_argument("--data_dir", type=str) 226 | parser.add_argument("--save_dir", type=str) 227 | args = parser.parse_args() 228 | os.makedirs(args.save_dir, exist_ok=True) 229 | curate_seqtopv2(args.data_dir, args.save_dir) 230 | 231 | 232 | 233 | -------------------------------------------------------------------------------- /llm-based-generation/llm-data-gen.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | import jsonlines 4 | import os 5 | import time 6 | 7 | import requests 8 | from dotenv import load_dotenv 9 | from tqdm import tqdm 10 | 11 | 12 | class GENAI: 13 | def __init__(self, model) -> None: 14 | self.model = model 15 | env_path = "../.env" 16 | load_dotenv(env_path) 17 | self.API_KEY = os.getenv("GENAI_KEY", None) 18 | self.URL = os.getenv("GENAI_API", None) 19 | 20 | def ask_batch(self, prompt, temperature=0.7, max_new_tokens=128, greedy=True): 21 | headers = { 22 | 'Content-Type': 'application/json', 23 | 'Authorization': f'Bearer {self.API_KEY}' 24 | } 25 | decoding_method = 'greedy' if greedy else 'sample' 26 | data = { 27 | "model_id": self.model, 28 | "inputs": prompt, 29 | "parameters": { 30 | "temperature": temperature, 31 | "max_new_tokens": max_new_tokens, 32 | "decoding_method": decoding_method 33 | } 34 | } 35 | response = requests.post(self.URL, headers=headers, data=json.dumps(data)) 36 | output_list = [x['generated_text'] for x in response.json()['results']] 37 | return output_list 38 | 39 | 40 | def generate_llm_paraphrase(api_str_list, save_path, model): 41 | def chunk_list(lst, chunk_size): 42 | return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)] 43 | 44 | single_api_str_list = [api.split('[SEP]') for api in api_str_list] 45 | single_api_str_list = [item.strip() for sublist in single_api_str_list for item in sublist] # flatten 46 | genai_obj = GENAI(model=model) # model can be any generative model 47 | api_to_str = {} 48 | chunked_list = chunk_list(single_api_str_list, 5) # chucked api lists with batch size 5 49 | for idx, batch in enumerate(chunked_list): 50 | print(f'Processing batch {idx} out of {len(chunked_list)}') 51 | prompts = [] 52 | for api in batch: 53 | output_string = f'intent: {api}' 54 | prompt = f'Convert the following intent and its parameteres into an imperative sentence. Do not copy the API or its parameters as is in the output sentence.\n\nInput:\n' + output_string + '\nOutput:\n' 55 | prompts.append(prompt) 56 | try: 57 | outputs = genai_obj.ask_batch(prompts) 58 | except: 59 | print('Connection error at ask_batch') 60 | time.sleep(5) 61 | outputs = genai_obj.ask_batch(prompts) 62 | for txt, api in zip(outputs, batch): 63 | api_to_str[api] = txt 64 | # uncomment to save llm phrases with interval of 100 batches 65 | # if len(api_to_str) > 0 and len(api_to_str) % 100 == 0: 66 | # with open(save_path, 'w+') as file: 67 | # json.dump(api_to_str, file, indent=4) 68 | # uncomment to save all llm phrases 69 | # with open(save_path, 'w+') as file: 70 | # json.dump(api_to_str, file, indent=4) 71 | return api_to_str 72 | 73 | 74 | def extract_raw_data(raw_data_dir): 75 | data_files = [item for item in os.listdir(raw_data_dir) if 76 | os.path.isfile(os.path.join(raw_data_dir, item)) and not item == 'schema.json'] 77 | processed_data = [] 78 | for file in tqdm(data_files): 79 | print(file) 80 | data = json.load(open(os.path.join(raw_data_dir, file))) 81 | print(len(data)) 82 | for d in tqdm(data): # each dialog 83 | for t in d['turns']: # each turns 84 | if t['speaker'] == 'USER': 85 | turn_intent_slots = [] 86 | for f in t['frames']: 87 | if f['state']['slot_values'] and not f['state']['active_intent'] == 'NONE': 88 | turn_slots = [] 89 | for slot, values in f['state']['slot_values'].items(): 90 | turn_slots.append(f'{slot} = {values[0]}') 91 | slot_str = ' ; '.join(turn_slots) 92 | turn_intent_slots.append(f"{f['state']['active_intent']}({slot_str})") 93 | api_str = ' [SEP] '.join(turn_intent_slots) 94 | processed_data.append({ 95 | 'dialog_id': d['dialogue_id'], 96 | 'speaker': 'USER', 97 | 'input': t['utterance'], 98 | 'output': api_str 99 | }) 100 | else: 101 | processed_data.append({ 102 | 'dialog_id': d['dialogue_id'], 103 | 'speaker': 'BOT', 104 | 'input': t['utterance'], 105 | 'output': '' 106 | }) 107 | return processed_data 108 | 109 | 110 | def curate_llm_based_data(data_dir_root, save_dir, dataset_name, model): 111 | os.makedirs(save_dir, exist_ok=True) 112 | splits = ['train', 'test', 'dev'] 113 | for split in splits: 114 | print(f'======= {split} =======') 115 | data_dir = os.path.join(data_dir_root, split) 116 | raw_data = extract_raw_data(data_dir) # combine multiple dialog files 117 | 118 | # uncomment to save intermediate data (raw data) 119 | # raw_save_path = os.path.join(save_dir, f'{dataset_name}-raw-{split}.jsonl') 120 | # with jsonlines.open(raw_save_path, "w") as writer: 121 | # writer.write_all(raw_data) 122 | 123 | api_str_list, api_str_dialog_map = [], {} 124 | for d in raw_data: 125 | if d['output'] and 'NONE(' not in d['output']: 126 | api_str_list.append(d['output']) 127 | api_str_dialog_map.setdefault(d['dialog_id'], []).append(d['output']) 128 | 129 | llm_paraphrase_save_path = os.path.join(save_dir, f'{dataset_name}-llm-{split}.jsonl') 130 | api_to_str = generate_llm_paraphrase(api_str_list, llm_paraphrase_save_path, model) 131 | 132 | # reconstruct the data with llm-paraphrases 133 | processed_data_dict_list = [] 134 | for _, conv in api_str_dialog_map.items(): 135 | input_list, output_list, api_list, intents = [], [], [], [] 136 | for apis in conv: 137 | api_list.extend(apis.split('[SEP]')) 138 | for api in api_list: 139 | intent = api[:api.index('(')] 140 | if intent not in intents: 141 | intents.append(intent) 142 | api_list = [max([api for api in api_list if api.startswith(intent)], key=len) for intent in 143 | intents] # take the longest string of intents (more slots). 144 | for api in api_list: 145 | if api in api_to_str.keys(): 146 | output_list.append(api) 147 | api_str = api_to_str[api].lower() 148 | api_str = api_str + '.' if not api_str.endswith('.') else api_str 149 | input_list.append(api_str) 150 | if input_list and output_list: 151 | processed_data_dict_list.append( 152 | { 153 | 'input': ' '.join(input_list), 154 | 'output': ' [SEP] '.join(output_list) 155 | } 156 | ) 157 | 158 | # save processed outputs 159 | processed_data_save_path = os.path.join(save_dir, f'{dataset_name}-processed-{split}.jsonl') 160 | with jsonlines.open(processed_data_save_path, "w") as writer: 161 | writer.write_all(processed_data_dict_list) 162 | 163 | 164 | if __name__ == '__main__': 165 | parser = argparse.ArgumentParser() 166 | parser.add_argument("--data_dir", type=str) 167 | parser.add_argument("--save_dir", type=str) 168 | parser.add_argument("--dataset_name", type=str) 169 | parser.add_argument("--model", type=str) 170 | args = parser.parse_args() 171 | curate_llm_based_data(args.data_dir, args.save_dir, args.dataset_name, args.model) 172 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | jsonlines==4.0.0 2 | requests==2.31.0 3 | tqdm==4.66.2 4 | python-dotenv==1.0.1 5 | spacy==3.7.2 6 | nltk==3.8.1 7 | rapidfuzz==3.6.2 8 | chardet==5.2.0 --------------------------------------------------------------------------------