├── README.md
├── LICENSE
└── code
└── simQUAC.py
/README.md:
--------------------------------------------------------------------------------
1 | [](https://zenodo.org/doi/10.5281/zenodo.10838996)
2 |
3 | # SimQUAC
4 |
5 | This repository includes the code and datasets for the paper SimQUAC: Let the LLMs Talk: Simulating Human-to-Human Conversational QA via Zero-Shot LLM-to-LLM Interactions.
6 | You can download the paper here.
7 |
8 |
9 | ----
10 | ### Datasets
11 | The ``Teache_sim_50_topics.txt`` includes the answers generated by Teacher_sim for a subset of 50 topics from QUAC train dataset.
12 |
13 | The ``quac_subset.json`` includes 370 conversations from QUAC train set.
14 |
15 | The ``quac_subset.json`` file includes conversations generated by SimQUAC simulator on the same topics.
16 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Creative Commons Legal Code
2 |
3 | CC0 1.0 Universal
4 |
5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12 | HEREUNDER.
13 |
14 | Statement of Purpose
15 |
16 | The laws of most jurisdictions throughout the world automatically confer
17 | exclusive Copyright and Related Rights (defined below) upon the creator
18 | and subsequent owner(s) (each and all, an "owner") of an original work of
19 | authorship and/or a database (each, a "Work").
20 |
21 | Certain owners wish to permanently relinquish those rights to a Work for
22 | the purpose of contributing to a commons of creative, cultural and
23 | scientific works ("Commons") that the public can reliably and without fear
24 | of later claims of infringement build upon, modify, incorporate in other
25 | works, reuse and redistribute as freely as possible in any form whatsoever
26 | and for any purposes, including without limitation commercial purposes.
27 | These owners may contribute to the Commons to promote the ideal of a free
28 | culture and the further production of creative, cultural and scientific
29 | works, or to gain reputation or greater distribution for their Work in
30 | part through the use and efforts of others.
31 |
32 | For these and/or other purposes and motivations, and without any
33 | expectation of additional consideration or compensation, the person
34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35 | is an owner of Copyright and Related Rights in the Work, voluntarily
36 | elects to apply CC0 to the Work and publicly distribute the Work under its
37 | terms, with knowledge of his or her Copyright and Related Rights in the
38 | Work and the meaning and intended legal effect of CC0 on those rights.
39 |
40 | 1. Copyright and Related Rights. A Work made available under CC0 may be
41 | protected by copyright and related or neighboring rights ("Copyright and
42 | Related Rights"). Copyright and Related Rights include, but are not
43 | limited to, the following:
44 |
45 | i. the right to reproduce, adapt, distribute, perform, display,
46 | communicate, and translate a Work;
47 | ii. moral rights retained by the original author(s) and/or performer(s);
48 | iii. publicity and privacy rights pertaining to a person's image or
49 | likeness depicted in a Work;
50 | iv. rights protecting against unfair competition in regards to a Work,
51 | subject to the limitations in paragraph 4(a), below;
52 | v. rights protecting the extraction, dissemination, use and reuse of data
53 | in a Work;
54 | vi. database rights (such as those arising under Directive 96/9/EC of the
55 | European Parliament and of the Council of 11 March 1996 on the legal
56 | protection of databases, and under any national implementation
57 | thereof, including any amended or successor version of such
58 | directive); and
59 | vii. other similar, equivalent or corresponding rights throughout the
60 | world based on applicable law or treaty, and any national
61 | implementations thereof.
62 |
63 | 2. Waiver. To the greatest extent permitted by, but not in contravention
64 | of, applicable law, Affirmer hereby overtly, fully, permanently,
65 | irrevocably and unconditionally waives, abandons, and surrenders all of
66 | Affirmer's Copyright and Related Rights and associated claims and causes
67 | of action, whether now known or unknown (including existing as well as
68 | future claims and causes of action), in the Work (i) in all territories
69 | worldwide, (ii) for the maximum duration provided by applicable law or
70 | treaty (including future time extensions), (iii) in any current or future
71 | medium and for any number of copies, and (iv) for any purpose whatsoever,
72 | including without limitation commercial, advertising or promotional
73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74 | member of the public at large and to the detriment of Affirmer's heirs and
75 | successors, fully intending that such Waiver shall not be subject to
76 | revocation, rescission, cancellation, termination, or any other legal or
77 | equitable action to disrupt the quiet enjoyment of the Work by the public
78 | as contemplated by Affirmer's express Statement of Purpose.
79 |
80 | 3. Public License Fallback. Should any part of the Waiver for any reason
81 | be judged legally invalid or ineffective under applicable law, then the
82 | Waiver shall be preserved to the maximum extent permitted taking into
83 | account Affirmer's express Statement of Purpose. In addition, to the
84 | extent the Waiver is so judged Affirmer hereby grants to each affected
85 | person a royalty-free, non transferable, non sublicensable, non exclusive,
86 | irrevocable and unconditional license to exercise Affirmer's Copyright and
87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the
88 | maximum duration provided by applicable law or treaty (including future
89 | time extensions), (iii) in any current or future medium and for any number
90 | of copies, and (iv) for any purpose whatsoever, including without
91 | limitation commercial, advertising or promotional purposes (the
92 | "License"). The License shall be deemed effective as of the date CC0 was
93 | applied by Affirmer to the Work. Should any part of the License for any
94 | reason be judged legally invalid or ineffective under applicable law, such
95 | partial invalidity or ineffectiveness shall not invalidate the remainder
96 | of the License, and in such case Affirmer hereby affirms that he or she
97 | will not (i) exercise any of his or her remaining Copyright and Related
98 | Rights in the Work or (ii) assert any associated claims and causes of
99 | action with respect to the Work, in either case contrary to Affirmer's
100 | express Statement of Purpose.
101 |
102 | 4. Limitations and Disclaimers.
103 |
104 | a. No trademark or patent rights held by Affirmer are waived, abandoned,
105 | surrendered, licensed or otherwise affected by this document.
106 | b. Affirmer offers the Work as-is and makes no representations or
107 | warranties of any kind concerning the Work, express, implied,
108 | statutory or otherwise, including without limitation warranties of
109 | title, merchantability, fitness for a particular purpose, non
110 | infringement, or the absence of latent or other defects, accuracy, or
111 | the present or absence of errors, whether or not discoverable, all to
112 | the greatest extent permissible under applicable law.
113 | c. Affirmer disclaims responsibility for clearing rights of other persons
114 | that may apply to the Work or any use thereof, including without
115 | limitation any person's Copyright and Related Rights in the Work.
116 | Further, Affirmer disclaims responsibility for obtaining any necessary
117 | consents, permissions or other rights required for any use of the
118 | Work.
119 | d. Affirmer understands and acknowledges that Creative Commons is not a
120 | party to this document and has no duty or obligation with respect to
121 | this CC0 or use of the Work.
122 |
--------------------------------------------------------------------------------
/code/simQUAC.py:
--------------------------------------------------------------------------------
1 | import openai
2 | import nltk
3 | import re
4 | import random
5 | import pickle
6 |
7 | def get_topics(path_to_topics):
8 |
9 | with open(path_to_topics, "r") as r:
10 | data = r.read()
11 |
12 | topics = data.strip().split(TOPIC_SPLITTER)
13 | topics = [topic.strip() for topic in topics if len(topic.strip())>0]
14 |
15 | return topics
16 |
17 | def run_gpt4(conversation_Log):
18 | response = openai.ChatCompletion.create(
19 | model=model_id,
20 | messages=conversation_Log
21 | )
22 |
23 | return response.choices[0].message.role, response.choices[0].message.content.strip()
24 |
25 | def pre_process_res(response_text):
26 | if response_text.startswith("Text:"):
27 | response_text = response_text.lstrip("Text:")
28 |
29 | response_text = response_text.strip()
30 | response_text = response_text.rstrip(",.;:?!\"\'")
31 | response_text = response_text.lstrip(",.;:?!\"\'")
32 |
33 | return response_text
34 |
35 | def get_grounded_answers(answer_text, section_text):
36 | sentences = nltk.sent_tokenize(answer_text)
37 | curr_sent = sentences[0]
38 | answers_all = []
39 |
40 | for i in range(1, len(sentences)):
41 | x_1 = (curr_sent.strip() + " " + sentences[i].strip())
42 | if (x_1 in section_text):
43 | curr_sent = x_1
44 | else:
45 | answers_all.append(curr_sent)
46 | curr_sent = sentences[i]
47 |
48 | if not (curr_sent in answers_all):
49 | answers_all.append(curr_sent)
50 |
51 | return answers_all
52 |
53 | def check_overlap(answer_text, section_text):
54 | length = len(answer_text.split())
55 | tmp = answer_text
56 | for i in range(0, int(length/2)):
57 | tmp = tmp.split(' ', 1)[1]
58 | if tmp.lower() in section_text.lower():
59 | return True, tmp
60 | return False, None
61 |
62 | def check_teacher_response(response, topic_background, section):
63 | response = pre_process_res(response)
64 |
65 | # condition 0
66 | if (response in cannot_find_text) or (cannot_find_text in response) or ("the text does not" in response):
67 | print("Condition 0")
68 | return True, [cannot_find_text]
69 |
70 | # condition 1
71 | res, tmp_text = check_overlap(response, section)
72 | if res:
73 | print("Condition 1")
74 | return True, [tmp_text]
75 |
76 | # condition 2
77 | clean_section = re.sub("([\(\[]).*?([\)\]])", "\g<1>\g<2>", section)
78 | clean_section = ' '.join(clean_section.split())
79 |
80 | res, tmp_text = check_overlap(response, clean_section)
81 | if res:
82 | print("Condition 2")
83 | return True, [tmp_text]
84 |
85 | # condition 3
86 | sentencess = get_grounded_answers(response, section)
87 |
88 | answer_spans = []
89 |
90 | for sent in sentencess:
91 | if len(sent) > 0:
92 | sent_clean = pre_process_res(sent)
93 | res, tmp_text = check_overlap(sent_clean, section)
94 | if res:
95 | answer_spans.append(tmp_text)
96 |
97 | if len(answer_spans) > 0:
98 | print("Condition 3")
99 | return True, answer_spans
100 |
101 | # condition 5
102 | if response in topic_background:
103 | print("Condition 4")
104 | return False, [prompt_answer_from_text]
105 |
106 | return False, [prompt_copy_exact_segment]
107 |
108 | def teacher_process_one_question(index, doc_info, question):
109 |
110 | title, background, header, section = doc_info
111 |
112 | if index == 0:
113 | prompt_input = first_prompt_teacher.format(title=title, background=background, instruction_teacher= instruction_teacher, header=header, section=section, question=question)
114 |
115 | else:
116 | prompt_input = prompt_answer_short.format(question=question)
117 |
118 | teacher_conversations.append({'role': 'user', 'content': prompt_input})
119 |
120 | for i in range(0, TEACHER_PATIENCE):
121 | role, content = run_gpt4(teacher_conversations)
122 | teacher_conversations.append({'role': role, 'content': content})
123 | res, res_prompt = check_teacher_response(content, doc_info[1], doc_info[3])
124 |
125 | if res == True:
126 | gpt_4_answer = res_prompt
127 | break
128 |
129 | elif i < 3:
130 | # ask the given prompt
131 | teacher_conversations.append({'role': 'user', 'content': res_prompt[0]})
132 |
133 | elif i == 3:
134 | gpt_4_answer = ["I cannot find the answer. " + content]
135 | print("final answer didn't match!")
136 |
137 | return gpt_4_answer
138 |
139 | def check_question(question):
140 | if "\n" in question or len(question.split()) > MAX_QUES_LENGTH:
141 | return False
142 | return True
143 |
144 | def simulate_student(first_question, title, background, header, prev_answer, prompt_arr_student):
145 |
146 | if first_question:
147 | prompt = student_prompt.format(instruction=student_instruction, title=title, background=background, header=header)
148 |
149 | elif prev_answer == cannot_find_text:
150 | prompt = random.choice(prompt_arr_student)
151 | print("Student selected prompt: ", prompt)
152 | if prompt == interesting_prompt:
153 | prompt_arr_student.remove(interesting_prompt)
154 |
155 | else:
156 | prompt = student_prompt_regular
157 |
158 | answer_with_prompt = prev_answer + " " + prompt
159 | student_conversations.append({'role': 'user', 'content': answer_with_prompt})
160 | role, new_question = run_gpt4(student_conversations)
161 |
162 | while not check_question(new_question):
163 | role, new_question = run_gpt4(student_conversations)
164 | prompt_2 = answer_with_prompt + " Please only ask one short question."
165 | student_conversations[-1] = {'role': 'user', 'content': prompt_2}
166 |
167 | student_conversations.append({'role': role, 'content': new_question})
168 |
169 |
170 | if prompt == interesting_prompt:
171 | new_question = new_question + " (tell me maximum number of two segments)"
172 |
173 | return new_question
174 |
175 | def student_teacher_simulation(doc_info):
176 | output_res = {}
177 |
178 | prompt_arr_student = [wh_prompt, interesting_prompt, general_prompt, change_aspect]
179 | title, background, header, section = doc_info
180 |
181 | output_res['title'] = title
182 | output_res['background'] = background
183 | output_res['header'] = header
184 | output_res['section'] = section
185 | output_res['conversation'] = []
186 |
187 |
188 | question = simulate_student(True, title, background, header, "", prompt_arr_student)
189 | answer_arr = teacher_process_one_question(0, doc_info, question)
190 | tmp= {'question': question,
191 | 'answer':answer_arr}
192 | output_res['conversation'].append(tmp)
193 | answer = ' '.join(answer_arr)
194 |
195 | for i in range(1, CONV_LENGTH):
196 | question = simulate_student(False, title, background, header, answer, prompt_arr_student)
197 | answer_arr = teacher_process_one_question(i, doc_info, question)
198 | tmp = {'question': question,
199 | 'answer': answer_arr}
200 | output_res['conversation'].append(tmp)
201 | answer = ' '.join(answer_arr)
202 |
203 | return output_res
204 |
205 |
206 | prompt_answer_from_text = "Please answer from the given section not the given background description."
207 | prompt_copy_exact_segment = "Please copy the exact segment from the text."
208 | cannot_find_text = "I cannot find the answer."
209 | prompt_answer_short = "{question}\n(Remember that you should select the shortest possible span from the text)."
210 | student_prompt = "{instruction}\nBackground:\n:{title}\n{background}\nHeader: {header}\nPlease start asking questions about: {header}."
211 |
212 | student_instruction = """In this task, I am a teacher and have a document, you are a curious student who wants to explore this document by asking questions.
213 | The main objective is to learn most of the document that I have. I will give you background knowledge of the document and the title of the document.
214 | You should ask questions about this title one by one. When you ask a question, I give you the answer, and then you ask your next question.
215 | I’m only allowed to find the answer to your questions from this document, so if I cannot find the answer, I will say “I cannot find the answer, please ask your next question”.
216 | You shouldn’t ask questions that can be answered from my previous answers to your previous questions. You should sometimes ask follow-up questions from my previous answers."""
217 |
218 | general_prompt = "Please ask a general question and don't ask a too specific question."
219 | wh_prompt = "Please ask a question starting with where, when, or who."
220 | interesting_prompt = "Please ask what is interesting about this document."
221 | change_aspect = "Please ask a question about another aspect of the topic."
222 | student_prompt_regular = ". Please ask your next question."
223 | prompt_without_ellipsis = "Please repeat your last question by using Ellipsis and co-references."
224 |
225 | API_key = ""
226 | openai.api_key = API_key
227 | model_id = "gpt-4"
228 | path_to_topics = "./data_for_simulation.txt"
229 | result_path = './simulated_conversations'
230 | TOPIC_SPLITTER = ""
231 |
232 | TEACHER_PATIENCE = 4
233 | MAX_QUES_LENGTH = 25
234 | CONV_LENGTH = 12
235 |
236 | instruction_teacher = """In this task, you will be given a text about the topic explained above. You will answer my questions from this text. Please remember that you cannot generate the answer on your own but should only copy a continuous span from the original text and the copied answer should not exceed 40 tokens. If you cannot find the answer in the text, please generate ‘I cannot find the answer’."""
237 | first_prompt_teacher = "Topic: {title}\n{background}\n{instruction_teacher}\nText:\n{header}\n{section}\nQuestion: {question}"
238 |
239 | topics = get_topics(path_to_topics)
240 |
241 | simulated_convs = []
242 |
243 | for i in range(0, len(topics)):
244 | teacher_conversations = []
245 | student_conversations = []
246 | doc_info = topics[i].strip().split("\n")
247 | doc_info[3] = ' '.join(doc_info[3].split()).rstrip("CANNOTANSWER").strip()
248 | doc_info[1] = ' '.join(doc_info[1].split())
249 | output_res = student_teacher_simulation(doc_info)
250 | simulated_convs.append(output_res)
251 |
252 |
253 | with open(result_path, 'wb') as f:
254 | pickle.dump(simulated_convs)
255 |
256 |
--------------------------------------------------------------------------------