eval-framework 0.2.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. eval_framework/__init__.py +7 -0
  2. eval_framework/base_config.py +36 -0
  3. eval_framework/context/__init__.py +0 -0
  4. eval_framework/context/determined.py +177 -0
  5. eval_framework/context/eval.py +121 -0
  6. eval_framework/context/local.py +78 -0
  7. eval_framework/evaluation_generator.py +234 -0
  8. eval_framework/exceptions.py +2 -0
  9. eval_framework/external/ifeval_impl/README.md +5 -0
  10. eval_framework/external/ifeval_impl/instructions.py +1523 -0
  11. eval_framework/external/ifeval_impl/instructions_registry.py +161 -0
  12. eval_framework/external/ifeval_impl/instructions_util.py +1689 -0
  13. eval_framework/external/ifeval_impl/utils.py +135 -0
  14. eval_framework/llm/__init__.py +0 -0
  15. eval_framework/llm/aleph_alpha.py +432 -0
  16. eval_framework/llm/base.py +180 -0
  17. eval_framework/llm/huggingface.py +418 -0
  18. eval_framework/llm/mistral.py +88 -0
  19. eval_framework/llm/models.py +28 -0
  20. eval_framework/llm/openai.py +400 -0
  21. eval_framework/llm/vllm.py +554 -0
  22. eval_framework/logger.py +3 -0
  23. eval_framework/main.py +166 -0
  24. eval_framework/metrics/__init__.py +0 -0
  25. eval_framework/metrics/base.py +40 -0
  26. eval_framework/metrics/completion/__init__.py +1 -0
  27. eval_framework/metrics/completion/accuracy_completion.py +16 -0
  28. eval_framework/metrics/completion/aidanbench.py +28 -0
  29. eval_framework/metrics/completion/bleu.py +76 -0
  30. eval_framework/metrics/completion/chrf.py +62 -0
  31. eval_framework/metrics/completion/code_assertion.py +44 -0
  32. eval_framework/metrics/completion/code_execution_pass_at_one.py +126 -0
  33. eval_framework/metrics/completion/comet.py +56 -0
  34. eval_framework/metrics/completion/concordance_index.py +38 -0
  35. eval_framework/metrics/completion/csv_format.py +102 -0
  36. eval_framework/metrics/completion/cwe_accuracy.py +49 -0
  37. eval_framework/metrics/completion/exponential_similarity.py +65 -0
  38. eval_framework/metrics/completion/f1.py +42 -0
  39. eval_framework/metrics/completion/format_checker.py +56 -0
  40. eval_framework/metrics/completion/grid_difference.py +77 -0
  41. eval_framework/metrics/completion/ifeval.py +73 -0
  42. eval_framework/metrics/completion/json_format.py +179 -0
  43. eval_framework/metrics/completion/language_checker.py +74 -0
  44. eval_framework/metrics/completion/length_control.py +83 -0
  45. eval_framework/metrics/completion/math_reasoning_completion.py +307 -0
  46. eval_framework/metrics/completion/niah_accuracy.py +163 -0
  47. eval_framework/metrics/completion/placeholder_checker.py +27 -0
  48. eval_framework/metrics/completion/repetition.py +88 -0
  49. eval_framework/metrics/completion/rouge_1.py +35 -0
  50. eval_framework/metrics/completion/rouge_2.py +45 -0
  51. eval_framework/metrics/completion/rouge_geometric_mean.py +36 -0
  52. eval_framework/metrics/completion/rouge_l.py +52 -0
  53. eval_framework/metrics/completion/struct_eval_metrics.py +248 -0
  54. eval_framework/metrics/completion/ter.py +67 -0
  55. eval_framework/metrics/completion/text_counter.py +182 -0
  56. eval_framework/metrics/efficiency/__init__.py +0 -0
  57. eval_framework/metrics/efficiency/bytes_per_sequence_position.py +48 -0
  58. eval_framework/metrics/llm/__init__.py +0 -0
  59. eval_framework/metrics/llm/base.py +34 -0
  60. eval_framework/metrics/llm/graders/chatbot_style_grader.py +92 -0
  61. eval_framework/metrics/llm/graders/coherence_grader.py +115 -0
  62. eval_framework/metrics/llm/graders/comparison_grader.py +198 -0
  63. eval_framework/metrics/llm/graders/conciseness_grader.py +93 -0
  64. eval_framework/metrics/llm/graders/contains_names_grader.py +71 -0
  65. eval_framework/metrics/llm/graders/format_correctness_grader.py +109 -0
  66. eval_framework/metrics/llm/graders/instruction_grader.py +177 -0
  67. eval_framework/metrics/llm/graders/language.py +56 -0
  68. eval_framework/metrics/llm/graders/long_context_grader.py +72 -0
  69. eval_framework/metrics/llm/graders/models.py +74 -0
  70. eval_framework/metrics/llm/graders/refusal_grader.py +57 -0
  71. eval_framework/metrics/llm/graders/sql_quality_grader.py +145 -0
  72. eval_framework/metrics/llm/graders/summary_world_knowledge_grader.py +103 -0
  73. eval_framework/metrics/llm/llm_judge_chatbot_style.py +36 -0
  74. eval_framework/metrics/llm/llm_judge_coherence.py +44 -0
  75. eval_framework/metrics/llm/llm_judge_completion_accuracy.py +39 -0
  76. eval_framework/metrics/llm/llm_judge_conciseness.py +37 -0
  77. eval_framework/metrics/llm/llm_judge_contains_names.py +36 -0
  78. eval_framework/metrics/llm/llm_judge_format_correctness.py +43 -0
  79. eval_framework/metrics/llm/llm_judge_instruction.py +58 -0
  80. eval_framework/metrics/llm/llm_judge_mtbench_pair.py +306 -0
  81. eval_framework/metrics/llm/llm_judge_mtbench_single.py +210 -0
  82. eval_framework/metrics/llm/llm_judge_refusal.py +35 -0
  83. eval_framework/metrics/llm/llm_judge_sql.py +394 -0
  84. eval_framework/metrics/llm/llm_judge_world_knowledge.py +37 -0
  85. eval_framework/metrics/llm/utils.py +20 -0
  86. eval_framework/metrics/loglikelihood/__init__.py +0 -0
  87. eval_framework/metrics/loglikelihood/accuracy_loglikelihood.py +51 -0
  88. eval_framework/metrics/loglikelihood/base.py +50 -0
  89. eval_framework/metrics/loglikelihood/confidence_weighted_accuracy.py +25 -0
  90. eval_framework/metrics/loglikelihood/dcs.py +43 -0
  91. eval_framework/metrics/loglikelihood/probability_mass.py +53 -0
  92. eval_framework/metrics/loglikelihood/ternary.py +42 -0
  93. eval_framework/py.typed +0 -0
  94. eval_framework/response_generator.py +351 -0
  95. eval_framework/result_processors/__init__.py +0 -0
  96. eval_framework/result_processors/base.py +88 -0
  97. eval_framework/result_processors/hf_uploader.py +75 -0
  98. eval_framework/result_processors/result_processor.py +129 -0
  99. eval_framework/result_processors/wandb_uploader.py +137 -0
  100. eval_framework/run.py +369 -0
  101. eval_framework/run_direct.py +42 -0
  102. eval_framework/shared/types.py +227 -0
  103. eval_framework/tasks/__init__.py +6 -0
  104. eval_framework/tasks/base.py +392 -0
  105. eval_framework/tasks/benchmarks/__init__.py +0 -0
  106. eval_framework/tasks/benchmarks/aidanbench.py +211 -0
  107. eval_framework/tasks/benchmarks/arc.py +70 -0
  108. eval_framework/tasks/benchmarks/arc_de.py +46 -0
  109. eval_framework/tasks/benchmarks/arc_fi.py +46 -0
  110. eval_framework/tasks/benchmarks/belebele.py +60 -0
  111. eval_framework/tasks/benchmarks/bigcodebench.py +155 -0
  112. eval_framework/tasks/benchmarks/casehold.py +47 -0
  113. eval_framework/tasks/benchmarks/chembench.py +85 -0
  114. eval_framework/tasks/benchmarks/copa.py +64 -0
  115. eval_framework/tasks/benchmarks/duc.py +91 -0
  116. eval_framework/tasks/benchmarks/flores200.py +133 -0
  117. eval_framework/tasks/benchmarks/flores_plus.py +84 -0
  118. eval_framework/tasks/benchmarks/gpqa.py +201 -0
  119. eval_framework/tasks/benchmarks/gsm8k.py +150 -0
  120. eval_framework/tasks/benchmarks/hellaswag.py +69 -0
  121. eval_framework/tasks/benchmarks/hellaswag_de.py +52 -0
  122. eval_framework/tasks/benchmarks/humaneval.py +97 -0
  123. eval_framework/tasks/benchmarks/ifeval.py +78 -0
  124. eval_framework/tasks/benchmarks/include.py +119 -0
  125. eval_framework/tasks/benchmarks/infinitebench.py +302 -0
  126. eval_framework/tasks/benchmarks/math_reasoning.py +580 -0
  127. eval_framework/tasks/benchmarks/mbpp.py +192 -0
  128. eval_framework/tasks/benchmarks/mmlu.py +215 -0
  129. eval_framework/tasks/benchmarks/mmlu_de.py +109 -0
  130. eval_framework/tasks/benchmarks/mmlu_pro.py +164 -0
  131. eval_framework/tasks/benchmarks/mmmlu.py +529 -0
  132. eval_framework/tasks/benchmarks/openbookqa.py +85 -0
  133. eval_framework/tasks/benchmarks/opengptx_eu20.py +363 -0
  134. eval_framework/tasks/benchmarks/pawsx.py +65 -0
  135. eval_framework/tasks/benchmarks/piqa.py +64 -0
  136. eval_framework/tasks/benchmarks/quality.py +56 -0
  137. eval_framework/tasks/benchmarks/sciq.py +110 -0
  138. eval_framework/tasks/benchmarks/sphyr.py +79 -0
  139. eval_framework/tasks/benchmarks/squad.py +211 -0
  140. eval_framework/tasks/benchmarks/struct_eval.py +116 -0
  141. eval_framework/tasks/benchmarks/tablebench.py +117 -0
  142. eval_framework/tasks/benchmarks/triviaqa.py +42 -0
  143. eval_framework/tasks/benchmarks/truthfulqa.py +119 -0
  144. eval_framework/tasks/benchmarks/winogender.py +64 -0
  145. eval_framework/tasks/benchmarks/winogrande.py +69 -0
  146. eval_framework/tasks/benchmarks/winox.py +57 -0
  147. eval_framework/tasks/benchmarks/wmt.py +160 -0
  148. eval_framework/tasks/benchmarks/zero_scrolls.py +197 -0
  149. eval_framework/tasks/eval_config.py +136 -0
  150. eval_framework/tasks/perturbation.py +83 -0
  151. eval_framework/tasks/registry.py +186 -0
  152. eval_framework/tasks/task_loader.py +81 -0
  153. eval_framework/tasks/task_names.py +324 -0
  154. eval_framework/tasks/utils.py +584 -0
  155. eval_framework/utils/constants.py +9 -0
  156. eval_framework/utils/file_ops.py +245 -0
  157. eval_framework/utils/generate_task_docs.py +244 -0
  158. eval_framework/utils/helpers.py +32 -0
  159. eval_framework/utils/logging.py +62 -0
  160. eval_framework/utils/packaging.py +52 -0
  161. eval_framework/utils/tqdm_handler.py +14 -0
  162. eval_framework-0.2.7.dist-info/METADATA +548 -0
  163. eval_framework-0.2.7.dist-info/RECORD +170 -0
  164. eval_framework-0.2.7.dist-info/WHEEL +4 -0
  165. eval_framework-0.2.7.dist-info/entry_points.txt +3 -0
  166. template_formatting/README.md +83 -0
  167. template_formatting/__init__.py +0 -0
  168. template_formatting/formatter.py +537 -0
  169. template_formatting/mistral_formatter.py +159 -0
  170. template_formatting/py.typed +0 -0
@@ -0,0 +1,1523 @@
1
+ # Copyright 2023 The Google Research Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # mypy: ignore-errors
16
+
17
+ """Library of instructions."""
18
+
19
+ import collections
20
+ import json
21
+ import logging
22
+ import random
23
+ import re
24
+ import string
25
+ from collections.abc import Sequence
26
+
27
+ import langdetect
28
+
29
+ from eval_framework.external.ifeval_impl import instructions_util
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ _InstructionArgsDtype = dict[str, int | str | Sequence[str]] | None
34
+
35
+ _LANGUAGES = instructions_util.LANGUAGE_CODES
36
+
37
+ # The relational operation for comparison.
38
+ _COMPARISON_RELATION = ("less than", "at least")
39
+
40
+ # The maximum number of sentences.
41
+ _MAX_NUM_SENTENCES = 20
42
+
43
+ # The number of placeholders.
44
+ _NUM_PLACEHOLDERS = 4
45
+
46
+ # The number of bullet lists.
47
+ _NUM_BULLETS = 5
48
+
49
+ # The options of constrained response.
50
+ _CONSTRAINED_RESPONSE_OPTIONS = (
51
+ "My answer is yes.",
52
+ "My answer is no.",
53
+ "My answer is maybe.",
54
+ )
55
+
56
+ # The options of starter keywords.
57
+ _STARTER_OPTIONS = (
58
+ "I would say",
59
+ "My answer is",
60
+ "I believe",
61
+ "In my opinion",
62
+ "I think",
63
+ "I reckon",
64
+ "I feel",
65
+ "From my perspective",
66
+ "As I see it",
67
+ "According to me",
68
+ "As far as I'm concerned",
69
+ "To my understanding",
70
+ "In my view",
71
+ "My take on it is",
72
+ "As per my perception",
73
+ )
74
+
75
+ # The options of ending keywords.
76
+ _ENDING_OPTIONS = ("Any other questions?", "Is there anything else I can help with?")
77
+
78
+ # The number of highlighted sections.
79
+ _NUM_HIGHLIGHTED_SECTIONS = 4
80
+
81
+ # The section splitter.
82
+ _SECTION_SPLITER = ("Section", "SECTION")
83
+
84
+ # The number of sections.
85
+ _NUM_SECTIONS = 5
86
+
87
+ # The number of paragraphs.
88
+ _NUM_PARAGRAPHS = 5
89
+
90
+ # The postscript marker.
91
+ _POSTSCRIPT_MARKER = ("P.S.", "P.P.S")
92
+
93
+ # The number of keywords.
94
+ _NUM_KEYWORDS = 2
95
+
96
+ # The occurrences of a single keyword.
97
+ _KEYWORD_FREQUENCY = 3
98
+
99
+ # The occurrences of a single letter.
100
+ _LETTER_FREQUENCY = 10
101
+
102
+ # The occurrences of words with all capital letters.
103
+ _ALL_CAPITAL_WORD_FREQUENCY = 20
104
+
105
+ # The number of words in the response.
106
+ _NUM_WORDS_LOWER_LIMIT = 100
107
+ _NUM_WORDS_UPPER_LIMIT = 500
108
+
109
+
110
+ class Instruction:
111
+ """An instruction template."""
112
+
113
+ def __init__(self, instruction_id):
114
+ self.id = instruction_id
115
+
116
+ def build_description(self, **kwargs):
117
+ raise NotImplementedError("`build_description` not implemented.")
118
+
119
+ def get_instruction_args(self):
120
+ raise NotImplementedError("`get_instruction_args` not implemented.")
121
+
122
+ def get_instruction_args_keys(self):
123
+ raise NotImplementedError("`get_instruction_args_keys` not implemented.")
124
+
125
+ def check_following(self, value):
126
+ raise NotImplementedError("`check_following` not implemented.")
127
+
128
+
129
+ class ResponseLanguageChecker(Instruction):
130
+ """Check the language of the entire response."""
131
+
132
+ def build_description(self, *, language=None):
133
+ """Build the instruction description.
134
+
135
+ Args:
136
+ language: A string representing the expected language of the response. The
137
+ language has to comply to the 97 types defined in
138
+ `langid.py` (https://pypi.org/project/langid/1.1.5/), which follows
139
+ ISO 639-1 codes (https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes);
140
+ for example, `en` for English, `zh` for Chinese, `fr` for French.
141
+
142
+ Returns:
143
+ A string representing the instruction description.
144
+ """
145
+ self._language = language
146
+ if self._language is None:
147
+ self._language = random.choice(list(_LANGUAGES.keys()))
148
+ self._description_pattern = (
149
+ "Your ENTIRE response should be in {language} language, no other " + "language is allowed."
150
+ )
151
+ return self._description_pattern.format(language=_LANGUAGES[self._language])
152
+
153
+ def get_instruction_args(self):
154
+ """Returns the keyword args of `build_description`."""
155
+ return {"language": self._language}
156
+
157
+ def get_instruction_args_keys(self):
158
+ """Returns the args keys of `build_description`."""
159
+ return ["language"]
160
+
161
+ def check_following(self, value):
162
+ """Check if the language of the entire response follows the instruction.
163
+
164
+ Args:
165
+ value: A string representing the response.
166
+
167
+ Returns:
168
+ True if the language of `value` follows instruction; otherwise False.
169
+ """
170
+ assert isinstance(value, str)
171
+
172
+ try:
173
+ return langdetect.detect(value) == self._language
174
+ except langdetect.LangDetectException as e:
175
+ # Count as instruction is followed.
176
+ logging.error("Unable to detect language for text %s due to %s", value, e) # refex: disable=pytotw.037
177
+ return True
178
+
179
+
180
+ class NumberOfSentences(Instruction):
181
+ """Check the number of sentences."""
182
+
183
+ def build_description(self, *, num_sentences=None, relation=None):
184
+ """Build the instruction description.
185
+
186
+ Args:
187
+ num_sentences: An integer specifying the number of sentences as a
188
+ threshold.
189
+ relation: A string in (`less than`, `at least`), defining the relational
190
+ operator for comparison.
191
+ Two relational comparisons are supported for now:
192
+ if 'less than', the actual number of sentences < the threshold;
193
+ if 'at least', the actual number of sentences >= the threshold.
194
+
195
+ Returns:
196
+ A string representing the instruction description.
197
+ """
198
+ # The number of sentences as a threshold for comparison.
199
+ self._num_sentences_threshold = num_sentences
200
+ if self._num_sentences_threshold is None or self._num_sentences_threshold < 0:
201
+ self._num_sentences_threshold = random.randint(1, _MAX_NUM_SENTENCES)
202
+
203
+ if relation is None:
204
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
205
+ elif relation not in _COMPARISON_RELATION:
206
+ raise ValueError(
207
+ f"The supported relation for comparison must be in {_COMPARISON_RELATION}, but {relation} is given."
208
+ )
209
+ else:
210
+ self._comparison_relation = relation
211
+
212
+ self._description_pattern = "Your response should contain {relation} {num_sentences} sentences."
213
+ return self._description_pattern.format(
214
+ relation=self._comparison_relation,
215
+ num_sentences=self._num_sentences_threshold,
216
+ )
217
+
218
+ def get_instruction_args(self):
219
+ """Returns the keyword args of `build_description`."""
220
+ return {
221
+ "num_sentences": self._num_sentences_threshold,
222
+ "relation": self._comparison_relation,
223
+ }
224
+
225
+ def get_instruction_args_keys(self):
226
+ """Returns the args keys of `build_description`."""
227
+ return ["num_sentences", "relation"]
228
+
229
+ def check_following(self, value):
230
+ """Check if the number of sentences follows the instruction.
231
+
232
+ Args:
233
+ value: A string representing the response.
234
+
235
+ Returns:
236
+ True if the response follows the instruction.
237
+
238
+ Raise:
239
+ ValueError if the string in `instruction_args` is not in
240
+ [`less_than`, `at_least`].
241
+ """
242
+ num_sentences = instructions_util.count_sentences(value)
243
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
244
+ return num_sentences < self._num_sentences_threshold
245
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
246
+ return num_sentences >= self._num_sentences_threshold
247
+
248
+
249
+ class PlaceholderChecker(Instruction):
250
+ """Check the placeholders in template writing."""
251
+
252
+ def build_description(self, *, num_placeholders=None):
253
+ """Build the instruction description.
254
+
255
+ Args:
256
+ num_placeholders: An integer denoting the minimum number of
257
+ placeholders required in the response.
258
+
259
+ Returns:
260
+ A string representing the instruction description.
261
+ """
262
+ self._num_placeholders = num_placeholders
263
+ if self._num_placeholders is None or self._num_placeholders < 0:
264
+ self._num_placeholders = random.randint(1, _NUM_PLACEHOLDERS)
265
+ self._description_pattern = (
266
+ "The response must contain at least {num_placeholders} placeholders "
267
+ + "represented by square brackets, such as [address]."
268
+ )
269
+ return self._description_pattern.format(num_placeholders=self._num_placeholders)
270
+
271
+ def get_instruction_args(self):
272
+ """Returns the keyword args of `build_description`."""
273
+ return {"num_placeholders": self._num_placeholders}
274
+
275
+ def get_instruction_args_keys(self):
276
+ """Returns the args keys of `build_description`."""
277
+ return ["num_placeholders"]
278
+
279
+ def check_following(self, value):
280
+ """Check if the number of placeholders follows the instruction.
281
+
282
+ Args:
283
+ value: A string representing the response.
284
+
285
+ Returns:
286
+ True if the actual number of placeholders in the response is greater than
287
+ or equal to `num_placeholders`; otherwise, False.
288
+ """
289
+ placeholders = re.findall(r"\[.*?\]", value)
290
+ num_placeholders = len(placeholders)
291
+ return num_placeholders >= self._num_placeholders
292
+
293
+
294
+ class BulletListChecker(Instruction):
295
+ """Checks the bullet list in the prompt."""
296
+
297
+ def build_description(self, *, num_bullets=None):
298
+ """Build the instruction description.
299
+
300
+ Args:
301
+ num_bullets: An integer specifying the exact number of bullet lists
302
+ that is required to appear in the response.
303
+
304
+ Returns:
305
+ A string representing the instruction description.
306
+ """
307
+ self._num_bullets = num_bullets
308
+ if self._num_bullets is None or self._num_bullets < 0:
309
+ self._num_bullets = random.randint(1, _NUM_BULLETS)
310
+ self._description_pattern = (
311
+ "Your answer must contain exactly {num_bullets} bullet points. "
312
+ + "Use the markdown bullet points such as:\n"
313
+ + "* This is point 1. \n"
314
+ + "* This is point 2"
315
+ )
316
+ return self._description_pattern.format(num_bullets=self._num_bullets)
317
+
318
+ def get_instruction_args(self):
319
+ """Returns the keyword args of `build_description`."""
320
+ return {"num_bullets": self._num_bullets}
321
+
322
+ def get_instruction_args_keys(self):
323
+ """Returns the args keys of `build_description`."""
324
+ return ["num_bullets"]
325
+
326
+ def check_following(self, value):
327
+ r"""Check if the number of bullet lists meets the requirement.
328
+
329
+ Args:
330
+ value: A string representing the response. The response is expected to
331
+ contain some bullet lists that start with `\*`.
332
+
333
+ Returns:
334
+ True if the actual number of bullet lists in the response meets the
335
+ requirement.
336
+ """
337
+ bullet_lists = re.findall(r"^\s*\*[^\*].*$", value, flags=re.MULTILINE)
338
+ bullet_lists_2 = re.findall(r"^\s*-.*$", value, flags=re.MULTILINE)
339
+ num_bullet_lists = len(bullet_lists) + len(bullet_lists_2)
340
+ return num_bullet_lists == self._num_bullets
341
+
342
+
343
+ class ConstrainedResponseChecker(Instruction):
344
+ """Checks the constrained response."""
345
+
346
+ def build_description(self):
347
+ """Build the instruction description."""
348
+ # A sequence of string(s) representing the options of the expected response.
349
+ self._constrained_responses = _CONSTRAINED_RESPONSE_OPTIONS
350
+ self._description_pattern = "Answer with one of the following options: {response_options}"
351
+ return self._description_pattern.format(response_options=self._constrained_responses)
352
+
353
+ def get_instruction_args(self):
354
+ """Returns the keyword args of `build_description`."""
355
+ return None
356
+
357
+ def get_instruction_args_keys(self):
358
+ """Returns the args keys of `build_description`."""
359
+ return []
360
+
361
+ def check_following(self, value):
362
+ """Checks if the response matches the constrained options.
363
+
364
+ Args:
365
+ value: A string representing the response.
366
+
367
+ Returns:
368
+ True if the actual response contains one of the options in the constrained
369
+ responses; otherwise False.
370
+ """
371
+ value = value.strip()
372
+ for constrained_response in self._constrained_responses:
373
+ if constrained_response in value:
374
+ return True
375
+ return False
376
+
377
+
378
+ class ConstrainedStartChecker(Instruction):
379
+ """Checks the response start."""
380
+
381
+ def build_description(self, *, starter=None):
382
+ """Build the instruction description.
383
+
384
+ Args:
385
+ starter: A string representing the keyword that the response should start
386
+ with.
387
+
388
+ Returns:
389
+ A string representing the instruction description.
390
+ """
391
+ self._starter = starter.strip() if isinstance(starter, str) else starter
392
+ if self._starter is None:
393
+ self._starter = random.choice(_STARTER_OPTIONS)
394
+ self._description_pattern = (
395
+ "During the conversation, when it is your turn, " + "please always start with {starter}"
396
+ )
397
+ return self._description_pattern.format(starter=self._starter)
398
+
399
+ def get_instruction_args(self):
400
+ """Returns the keyword args of `build_description`."""
401
+ return {"starter": self._starter}
402
+
403
+ def get_instruction_args_keys(self):
404
+ """Returns the args keys of `build_description`."""
405
+ return ["starter"]
406
+
407
+ def check_following(self, value):
408
+ """Checks if the response starts with the constrained keyword or phrase.
409
+
410
+ Args:
411
+ value: A string representing the response.
412
+
413
+ Returns:
414
+ True if the response starts with the given phrase or keyword that is
415
+ contained in `instruction_args`; otherwise, False.
416
+ """
417
+ response_pattern = r"^\s*" + self._starter + r".*$"
418
+ response_with_constrained_start = re.search(response_pattern, value, flags=re.MULTILINE)
419
+ return True if response_with_constrained_start else False
420
+
421
+
422
+ class HighlightSectionChecker(Instruction):
423
+ """Checks the highlighted section."""
424
+
425
+ def build_description(self, *, num_highlights=None):
426
+ """Build the instruction description.
427
+
428
+ Args:
429
+ num_highlights: An integer specifying the minimum number of highlighted
430
+ sections.
431
+
432
+ Returns:
433
+ A string representing the instruction description.
434
+ """
435
+ self._num_highlights = num_highlights
436
+ if self._num_highlights is None or self._num_highlights < 0:
437
+ self._num_highlights = random.randint(1, _NUM_HIGHLIGHTED_SECTIONS)
438
+
439
+ self._description_pattern = (
440
+ "Highlight at least {num_highlights} sections in your answer with "
441
+ + "markdown, i.e. *highlighted section*."
442
+ )
443
+
444
+ return self._description_pattern.format(num_highlights=self._num_highlights)
445
+
446
+ def get_instruction_args(self):
447
+ """Returns the keyword args of `build_description`."""
448
+ return {"num_highlights": self._num_highlights}
449
+
450
+ def get_instruction_args_keys(self):
451
+ """Returns the args keys of `build_description`."""
452
+ return ["num_highlights"]
453
+
454
+ def check_following(self, value):
455
+ """Checks if the number of highlighted sections meets the requirement.
456
+
457
+ Args:
458
+ value: a string representing the response. The response is expected to
459
+ contain highlighted sections in the format of *highlighted*.
460
+
461
+ Returns:
462
+ True if the actual number of highlighted sections in the format of
463
+ *highlighted sections* meets the minimum requirement; otherwise False.
464
+ """
465
+ num_highlights = 0
466
+ highlights = re.findall(r"\*[^\n\*]*\*", value)
467
+ double_highlights = re.findall(r"\*\*[^\n\*]*\*\*", value)
468
+ for highlight in highlights:
469
+ if highlight.strip("*").strip():
470
+ num_highlights += 1
471
+ for highlight in double_highlights:
472
+ if highlight.removeprefix("**").removesuffix("**").strip():
473
+ num_highlights += 1
474
+
475
+ return num_highlights >= self._num_highlights
476
+
477
+
478
+ class SectionChecker(Instruction):
479
+ """Checks the sections."""
480
+
481
+ def build_description(self, *, section_spliter=None, num_sections=None):
482
+ """Build the instruction description.
483
+
484
+ Args:
485
+ section_spliter: A string represents the section spliter keyword that
486
+ marks a new section, i.e., `Section` or `SECTION`.
487
+ num_sections: An integer specifying the number of sections.
488
+
489
+ Returns:
490
+ A string representing the instruction description.
491
+ """
492
+ self._section_spliter = section_spliter.strip() if isinstance(section_spliter, str) else section_spliter
493
+ if self._section_spliter is None:
494
+ self._section_spliter = random.choice(_SECTION_SPLITER)
495
+
496
+ self._num_sections = num_sections
497
+ if self._num_sections is None or self._num_sections < 0:
498
+ self._num_sections = random.randint(1, _NUM_SECTIONS)
499
+
500
+ self._description_pattern = (
501
+ "Your response must have {num_sections} sections. Mark the beginning "
502
+ + "of each section with {section_spliter} X, such as:\n"
503
+ + "{section_spliter} 1\n"
504
+ + "[content of section 1]\n"
505
+ + "{section_spliter} 2\n"
506
+ + "[content of section 2]"
507
+ )
508
+
509
+ return self._description_pattern.format(num_sections=self._num_sections, section_spliter=self._section_spliter)
510
+
511
+ def get_instruction_args(self):
512
+ """Returns the keyword args of `build_description`."""
513
+ return {
514
+ "section_spliter": self._section_spliter,
515
+ "num_sections": self._num_sections,
516
+ }
517
+
518
+ def get_instruction_args_keys(self):
519
+ """Returns the args keys of `build_description`."""
520
+ return ["section_spliter", "num_sections"]
521
+
522
+ def check_following(self, value):
523
+ """Checks the response contains multiple sections.
524
+
525
+ Args:
526
+ value: A string representing the response. The response is expected
527
+ to contain multiple sections (number of sections is greater than 1).
528
+ A new section starts with `Section 1`, where the number denotes the
529
+ section index.
530
+
531
+ Returns:
532
+ True if the number of sections in the response is greater than or equal to
533
+ the minimum number of sections; otherwise, False.
534
+ """
535
+ section_splitter_patten = r"\s?" + self._section_spliter + r"\s?\d+\s?"
536
+ sections = re.split(section_splitter_patten, value)
537
+ num_sections = len(sections) - 1
538
+ return num_sections >= self._num_sections
539
+
540
+
541
+ class ParagraphChecker(Instruction):
542
+ """Checks the paragraphs."""
543
+
544
+ def build_description(self, *, num_paragraphs=None):
545
+ """Build the instruction description.
546
+
547
+ Args:
548
+ num_paragraphs: An integer specifying the number of paragraphs.
549
+
550
+ Returns:
551
+ A string representing the instruction description.
552
+ """
553
+ self._num_paragraphs = num_paragraphs
554
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
555
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
556
+
557
+ self._description_pattern = (
558
+ "There should be {num_paragraphs} paragraphs. " + "Paragraphs are separated with the markdown divider: ***"
559
+ )
560
+
561
+ return self._description_pattern.format(num_paragraphs=self._num_paragraphs)
562
+
563
+ def get_instruction_args(self):
564
+ """Returns the keyword args of `build_description`."""
565
+ return {"num_paragraphs": self._num_paragraphs}
566
+
567
+ def get_instruction_args_keys(self):
568
+ """Returns the args keys of `build_description`."""
569
+ return ["num_paragraphs"]
570
+
571
+ def check_following(self, value):
572
+ """Checks the response contains required number of paragraphs.
573
+
574
+ Args:
575
+ value: A string representing the response. The response may contain
576
+ paragraphs that are separated by the markdown divider: `***`.
577
+
578
+ Returns:
579
+ True if the actual number of paragraphs is the same as required;
580
+ otherwise, False.
581
+ """
582
+ paragraphs = re.split(r"\s?\*\*\*\s?", value)
583
+ num_paragraphs = len(paragraphs)
584
+
585
+ for index, paragraph in enumerate(paragraphs):
586
+ if not paragraph.strip():
587
+ if index == 0 or index == len(paragraphs) - 1:
588
+ num_paragraphs -= 1
589
+ else:
590
+ return False
591
+
592
+ return num_paragraphs == self._num_paragraphs
593
+
594
+
595
+ class PostscriptChecker(Instruction):
596
+ """Checks the postscript."""
597
+
598
+ def build_description(self, *, postscript_marker=None):
599
+ """Build the instruction description.
600
+
601
+ Args:
602
+ postscript_marker: A string containing the keyword that marks the start
603
+ of the postscript section.
604
+
605
+ Returns:
606
+ A string representing the instruction description.
607
+ """
608
+ self._postscript_marker = postscript_marker.strip() if isinstance(postscript_marker, str) else postscript_marker
609
+ if self._postscript_marker is None:
610
+ self._postscript_marker = random.choice(_POSTSCRIPT_MARKER)
611
+
612
+ self._description_pattern = (
613
+ "At the end of your response, please explicitly add a postscript " + "starting with {postscript}"
614
+ )
615
+
616
+ return self._description_pattern.format(postscript=self._postscript_marker)
617
+
618
+ def get_instruction_args(self):
619
+ """Returns the keyword args of `build_description`."""
620
+ return {"postscript_marker": self._postscript_marker}
621
+
622
+ def get_instruction_args_keys(self):
623
+ """Returns the args keys of `build_description`."""
624
+ return ["postscript_marker"]
625
+
626
+ def check_following(self, value):
627
+ """Checks if the response follows the postscript format.
628
+
629
+ Args:
630
+ value: a string representing the response. The response is expected to
631
+ contain a postscript section.
632
+
633
+ Returns:
634
+ True if the response contains a postscript section starting with
635
+ the keyword containing in the `instruction_args`; otherwise False.
636
+ """
637
+ value = value.lower()
638
+ if self._postscript_marker == "P.P.S":
639
+ postscript_pattern = r"\s*p\.\s?p\.\s?s.*$"
640
+ elif self._postscript_marker == "P.S.":
641
+ postscript_pattern = r"\s*p\.\s?s\..*$"
642
+ else:
643
+ postscript_pattern = r"\s*" + self._postscript_marker.lower() + r".*$"
644
+ postscript = re.findall(postscript_pattern, value, flags=re.MULTILINE)
645
+ return True if postscript else False
646
+
647
+
648
+ class RephraseChecker(Instruction):
649
+ """Checks the rephrase."""
650
+
651
+ def build_description(self, *, original_message):
652
+ """Build the instruction description.
653
+
654
+ Args:
655
+ original_message: A string representing the original message. The
656
+ rephrased response should only change its words/sentences in between
657
+ its two asterisks, for example, *change me*. Both original and rephrased
658
+ messages should contain the changes in the form of *change me*.
659
+
660
+ Returns:
661
+ A string representing the instruction description.
662
+ """
663
+ if not self.is_change(original_message):
664
+ raise ValueError(f"Message {original_message} does not contain changes in the form of *change me*.")
665
+
666
+ self._reference_without_change = original_message
667
+ self._description = (
668
+ "Rephrasing: Your rephrased response should only"
669
+ + "change the words/sentences in between two asterisks"
670
+ + "such as *change me*."
671
+ )
672
+ return self._description
673
+
674
+ def get_instruction_args(self):
675
+ """Returns the keyword args of `build_description`."""
676
+ return {"original_message": self._reference_without_change}
677
+
678
+ def get_instruction_args_keys(self):
679
+ """Returns the args keys of `build_description`."""
680
+ return ["original_message"]
681
+
682
+ def check_following(self, value):
683
+ r"""Checks if the rephrasing follows the instruction.
684
+
685
+ Args:
686
+ value: A string representing the response, which is expected to rephras
687
+ the string of `instruction_args`.
688
+
689
+ Returns:
690
+ True if `value` and `instruction_args` only differ by the words/sentences
691
+ in between two asterisks such as *change me*; otherwise, False.
692
+ """
693
+
694
+ if not self.is_change(value):
695
+ raise ValueError(f"value {value} does not contain changes in the form of *change me*.")
696
+
697
+ response_without_changes = self.strip_changes(value)
698
+ reference_without_changes = self.strip_changes(self._reference_without_change)
699
+
700
+ return response_without_changes == reference_without_changes
701
+
702
+ def is_change(self, response):
703
+ """Check if there is change in the response in the form of *change me*."""
704
+ return re.search(r"\*.*\*", response)
705
+
706
+ def strip_changes(self, response):
707
+ """Strips off the changes."""
708
+ return re.sub(r"\*.*\*", "", response)
709
+
710
+
711
+ class KeywordChecker(Instruction):
712
+ """Check the exisitence of certain keywords."""
713
+
714
+ def build_description(self, *, keywords=None):
715
+ """Build the instruction description.
716
+
717
+ Args:
718
+ keywords: A sequence of strings representing the keywords that are
719
+ expected in the response.
720
+
721
+ Returns:
722
+ A string representing the instruction description.
723
+ """
724
+
725
+ if not keywords:
726
+ self._keywords = instructions_util.generate_keywords(num_keywords=_NUM_KEYWORDS)
727
+ else:
728
+ self._keywords = keywords
729
+ self._keywords = sorted(self._keywords)
730
+
731
+ self._description_pattern = "Include keywords {keywords} in the response."
732
+
733
+ return self._description_pattern.format(keywords=self._keywords)
734
+
735
+ def get_instruction_args(self):
736
+ """Returns the keyword args of `build_description`."""
737
+ return {"keywords": self._keywords}
738
+
739
+ def get_instruction_args_keys(self):
740
+ """Returns the args keys of `build_description`."""
741
+ return ["keywords"]
742
+
743
+ def check_following(self, value):
744
+ """Check if the response contain the expected keywords."""
745
+ for keyword in self._keywords:
746
+ if not re.search(keyword, value, flags=re.IGNORECASE):
747
+ return False
748
+ return True
749
+
750
+
751
+ class KeywordFrequencyChecker(Instruction):
752
+ """Check the keyword frequency."""
753
+
754
+ def build_description(self, *, keyword=None, frequency=None, relation=None):
755
+ """Build the instruction description.
756
+
757
+ Args:
758
+ keyword: A string representing a keyword that is expected in the response.
759
+ frequency: An integer specifying the number of times `keyword` is expected
760
+ to appear in the response.
761
+ relation: A string in (`less than`, `at least`), defining the relational
762
+ operator for comparison.
763
+ Two relational comparisons are supported for now:
764
+ if 'less than', the actual number of occurrences < frequency;
765
+ if 'at least', the actual number of occurrences >= frequency.
766
+
767
+ Returns:
768
+ A string representing the instruction description.
769
+ """
770
+ if not keyword:
771
+ self._keyword = instructions_util.generate_keywords(num_keywords=1)[0]
772
+ else:
773
+ self._keyword = keyword.strip()
774
+
775
+ self._frequency = frequency
776
+ if self._frequency is None or self._frequency < 0:
777
+ self._frequency = random.randint(1, _KEYWORD_FREQUENCY)
778
+
779
+ if relation is None:
780
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
781
+ elif relation not in _COMPARISON_RELATION:
782
+ raise ValueError(
783
+ f"The supported relation for comparison must be in {_COMPARISON_RELATION}, but {relation} is given."
784
+ )
785
+ else:
786
+ self._comparison_relation = relation
787
+
788
+ self._description_pattern = (
789
+ "In your response, the word {keyword} should appear {relation} " + "{frequency} times."
790
+ )
791
+
792
+ return self._description_pattern.format(
793
+ keyword=self._keyword,
794
+ relation=self._comparison_relation,
795
+ frequency=self._frequency,
796
+ )
797
+
798
+ def get_instruction_args(self):
799
+ """Returns the keyword args of `build_description`."""
800
+ return {
801
+ "keyword": self._keyword,
802
+ "frequency": self._frequency,
803
+ "relation": self._comparison_relation,
804
+ }
805
+
806
+ def get_instruction_args_keys(self):
807
+ """Returns the args keys of `build_description`."""
808
+ return ["keyword", "frequency", "relation"]
809
+
810
+ def check_following(self, value):
811
+ """Checks if the response contain the keyword with required frequency."""
812
+ actual_occurrences = len(re.findall(self._keyword, value, flags=re.IGNORECASE))
813
+
814
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
815
+ return actual_occurrences < self._frequency
816
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
817
+ return actual_occurrences >= self._frequency
818
+
819
+
820
+ class NumberOfWords(Instruction):
821
+ """Checks the number of words."""
822
+
823
+ def build_description(self, *, num_words=None, relation=None):
824
+ """Build the instruction description.
825
+
826
+ Args:
827
+ num_words: An integer specifying the number of words contained in the
828
+ response.
829
+ relation: A string in (`less than`, `at least`), defining the relational
830
+ operator for comparison.
831
+ Two relational comparisons are supported for now:
832
+ if 'less than', the actual number of words < num_words;
833
+ if 'at least', the actual number of words >= num_words.
834
+
835
+ Returns:
836
+ A string representing the instruction description.
837
+ """
838
+
839
+ self._num_words = num_words
840
+ if self._num_words is None or self._num_words < 0:
841
+ self._num_words = random.randint(_NUM_WORDS_LOWER_LIMIT, _NUM_WORDS_UPPER_LIMIT)
842
+
843
+ if relation is None:
844
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
845
+ elif relation not in _COMPARISON_RELATION:
846
+ raise ValueError(
847
+ f"The supported relation for comparison must be in {_COMPARISON_RELATION}, but {relation} is given."
848
+ )
849
+ else:
850
+ self._comparison_relation = relation
851
+
852
+ self._description_pattern = "Answer with {relation} {num_words} words."
853
+
854
+ return self._description_pattern.format(relation=self._comparison_relation, num_words=self._num_words)
855
+
856
+ def get_instruction_args(self):
857
+ """Returns the keyword args of `build_description`."""
858
+ return {"num_words": self._num_words, "relation": self._comparison_relation}
859
+
860
+ def get_instruction_args_keys(self):
861
+ """Returns the args keys of `build_description`."""
862
+ return ["num_words", "relation"]
863
+
864
+ def check_following(self, value):
865
+ """Checks if the response contains the expected number of words."""
866
+ num_words = instructions_util.count_words(value)
867
+
868
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
869
+ return num_words < self._num_words
870
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
871
+ return num_words >= self._num_words
872
+
873
+
874
+ class JsonFormat(Instruction):
875
+ """Check the Json format."""
876
+
877
+ def build_description(self):
878
+ self._description_pattern = (
879
+ "Entire output should be wrapped in JSON format. You can use markdown ticks such as ```."
880
+ )
881
+ return self._description_pattern
882
+
883
+ def get_instruction_args(self):
884
+ """Returns the keyword args of `build_description`."""
885
+ return None
886
+
887
+ def get_instruction_args_keys(self):
888
+ """Returns the args keys of `build_description`."""
889
+ return []
890
+
891
+ def check_following(self, value):
892
+ value = (
893
+ value.strip()
894
+ .removeprefix("```json")
895
+ .removeprefix("```Json")
896
+ .removeprefix("```JSON")
897
+ .removeprefix("```")
898
+ .removesuffix("```")
899
+ .strip()
900
+ )
901
+ try:
902
+ json.loads(value)
903
+ except ValueError:
904
+ return False
905
+ return True
906
+
907
+
908
+ class ParagraphFirstWordCheck(Instruction):
909
+ """Check the paragraph and the first word of the nth paragraph."""
910
+
911
+ def build_description(self, num_paragraphs=None, nth_paragraph=None, first_word=None):
912
+ r"""Build the instruction description.
913
+
914
+ Args:
915
+ num_paragraphs: An integer indicating the number of paragraphs expected
916
+ in the response. A paragraph is a subset of the string that is
917
+ expected to be separated by '\n\n'.
918
+ nth_paragraph: An integer indicating the paragraph number that we look at.
919
+ Note that n starts from 1.
920
+ first_word: A string that represent the first word of the bth paragraph.
921
+
922
+ Returns:
923
+ A string representing the instruction description.
924
+ """
925
+ self._num_paragraphs = num_paragraphs
926
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
927
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
928
+
929
+ self._nth_paragraph = nth_paragraph
930
+ if self._nth_paragraph is None or self._nth_paragraph <= 0 or self._nth_paragraph > self._num_paragraphs:
931
+ self._nth_paragraph = random.randint(1, self._num_paragraphs + 1)
932
+
933
+ self._first_word = first_word
934
+ if self._first_word is None:
935
+ self._first_word = instructions_util.generate_keywords(num_keywords=1)[0]
936
+ self._first_word = self._first_word.lower()
937
+
938
+ self._description_pattern = (
939
+ "There should be {num_paragraphs} paragraphs. "
940
+ + "Paragraphs and only paragraphs are separated with each other by two "
941
+ + "new lines as if it was '\\n\\n' in python. "
942
+ + "Paragraph {nth_paragraph} must start with word {first_word}."
943
+ )
944
+
945
+ return self._description_pattern.format(
946
+ num_paragraphs=self._num_paragraphs,
947
+ nth_paragraph=self._nth_paragraph,
948
+ first_word=self._first_word,
949
+ )
950
+
951
+ def get_instruction_args(self):
952
+ """Returns the keyword args of `build_description`."""
953
+ return {
954
+ "num_paragraphs": self._num_paragraphs,
955
+ "nth_paragraph": self._nth_paragraph,
956
+ "first_word": self._first_word,
957
+ }
958
+
959
+ def get_instruction_args_keys(self):
960
+ """Returns the args keys of `build_description`."""
961
+ return ["num_paragraphs", "nth_paragraph", "first_word"]
962
+
963
+ def check_following(self, value):
964
+ """Checks for required number of paragraphs and correct first word.
965
+
966
+ Args:
967
+ value: a string representing the response. The response may contain
968
+ paragraphs that are separated by two new lines and the first word of
969
+ the nth paragraph will have to match a specified word.
970
+
971
+ Returns:
972
+ True if the number of paragraphs is the same as required and the first
973
+ word of the specified paragraph is the same as required. Otherwise, false.
974
+ """
975
+
976
+ paragraphs = re.split(r"\n\n", value)
977
+ num_paragraphs = len(paragraphs)
978
+
979
+ for paragraph in paragraphs:
980
+ if not paragraph.strip():
981
+ num_paragraphs -= 1
982
+
983
+ # check that index doesn't go out of bounds
984
+ if self._nth_paragraph <= num_paragraphs:
985
+ paragraph = paragraphs[self._nth_paragraph - 1].strip()
986
+ if not paragraph:
987
+ return False
988
+ else:
989
+ return False
990
+
991
+ first_word = ""
992
+ punctuation = {".", ",", "?", "!", "'", '"'}
993
+
994
+ # get first word and remove punctuation
995
+ word = paragraph.split()[0].strip()
996
+ word = word.lstrip("'")
997
+ word = word.lstrip('"')
998
+
999
+ for letter in word:
1000
+ if letter in punctuation:
1001
+ break
1002
+ first_word += letter.lower()
1003
+
1004
+ return num_paragraphs == self._num_paragraphs and first_word == self._first_word
1005
+
1006
+
1007
+ class KeySentenceChecker(Instruction):
1008
+ """Check the existence of certain key sentences."""
1009
+
1010
+ def build_description(self, key_sentences=None, num_sentences=None):
1011
+ """Build the instruction description.
1012
+
1013
+ Args:
1014
+ key_sentences: A sequences of strings representing the key sentences that
1015
+ are expected in the response.
1016
+ num_sentences: The number of key sentences that are expected to be seen in
1017
+ the response.
1018
+
1019
+ Returns:
1020
+ A string representing the instruction description.
1021
+ """
1022
+
1023
+ if not key_sentences:
1024
+ self._key_sentences = set(["For now, this is fine."])
1025
+ else:
1026
+ self._key_sentences = key_sentences
1027
+
1028
+ if not num_sentences:
1029
+ self._num_sentences = random.randint(1, len(self._key_sentences))
1030
+ else:
1031
+ self._num_sentences = num_sentences
1032
+
1033
+ self._description_pattern = "Include {num_sentences} of the following sentences {key_sentences}"
1034
+
1035
+ return self._description_pattern.format(num_sentences=self._num_sentences, key_sentences=self._key_sentences)
1036
+
1037
+ def get_instruction_args(self):
1038
+ """Returns the keyword args of `build_description`."""
1039
+ return {
1040
+ "num_sentences": self._num_sentences,
1041
+ "key_sentences": list(self._key_sentences),
1042
+ }
1043
+
1044
+ def get_instruction_args_keys(self):
1045
+ """Returns the args keys of `build_description`."""
1046
+ return ["num_sentences", "key_sentences"]
1047
+
1048
+ def check_following(self, value):
1049
+ """Checks if the response contains the expected key sentences."""
1050
+ count = 0
1051
+ sentences = instructions_util.split_into_sentences(value)
1052
+ for sentence in self._key_sentences:
1053
+ if sentence in sentences:
1054
+ count += 1
1055
+
1056
+ return count == self._num_sentences
1057
+
1058
+
1059
+ class ForbiddenWords(Instruction):
1060
+ """Checks that specified words are not used in response."""
1061
+
1062
+ def build_description(self, forbidden_words=None):
1063
+ """Build the instruction description.
1064
+
1065
+ Args:
1066
+ forbidden_words: A sequences of strings representing words that are not
1067
+ allowed in the response.
1068
+
1069
+ Returns:
1070
+ A string representing the instruction description.
1071
+ """
1072
+
1073
+ if not forbidden_words:
1074
+ self._forbidden_words = instructions_util.generate_keywords(num_keywords=_NUM_KEYWORDS)
1075
+ else:
1076
+ self._forbidden_words = list(set(forbidden_words))
1077
+ self._forbidden_words = sorted(self._forbidden_words)
1078
+ self._description_pattern = "Do not include keywords {forbidden_words} in the response."
1079
+
1080
+ return self._description_pattern.format(forbidden_words=self._forbidden_words)
1081
+
1082
+ def get_instruction_args(self):
1083
+ """Returns the keyword args of `build_description`."""
1084
+ return {"forbidden_words": self._forbidden_words}
1085
+
1086
+ def get_instruction_args_keys(self):
1087
+ """Returns the args keys of `build_description`."""
1088
+ return ["forbidden_words"]
1089
+
1090
+ def check_following(self, value):
1091
+ """Check if the response does not contain the expected keywords."""
1092
+ for word in self._forbidden_words:
1093
+ if re.search(r"\b" + word + r"\b", value, flags=re.IGNORECASE):
1094
+ return False
1095
+ return True
1096
+
1097
+
1098
+ class RephraseParagraph(Instruction):
1099
+ """Checks that the paragraph is rephrased."""
1100
+
1101
+ def build_description(self, *, original_paragraph, low, high):
1102
+ """Builds the instruction description.
1103
+
1104
+ Args:
1105
+ original_paragraph: A string presenting the original paragraph. The
1106
+ rephrases response should have betweeb low-high words in common.
1107
+ low: An integer presenting the lower bound of similar words.
1108
+ high: An integer representing the upper bound of similar words.
1109
+
1110
+ Returns:
1111
+ A string representing the instruction description.
1112
+ """
1113
+ self._original_paragraph = original_paragraph
1114
+ self._low = low
1115
+ self._high = high
1116
+
1117
+ self._description = (
1118
+ "Rephrase the following paragraph: "
1119
+ + "{original_paragraph}\nYour response should have "
1120
+ + "between {low} and {high} of the same words. "
1121
+ + "Words are the same if and only if all of the "
1122
+ + "letters, ignoring cases, are the same. For "
1123
+ + "example, 'run' is the same as 'Run' but different "
1124
+ + "to 'ran'."
1125
+ )
1126
+
1127
+ return self._description.format(original_paragraph=original_paragraph, low=self._low, high=self._high)
1128
+
1129
+ def get_instruction_args(self):
1130
+ """Returns the keyword args of `build_description`."""
1131
+ return {
1132
+ "original_paragraph": self._original_paragraph,
1133
+ "low": self._low,
1134
+ "high": self._high,
1135
+ }
1136
+
1137
+ def get_instruction_args_keys(self):
1138
+ """Returns the args keys of `build_description`."""
1139
+ return ["original_paragraph", "low", "high"]
1140
+
1141
+ def check_following(self, value):
1142
+ val_words = re.findall(r"\w+", value.lower())
1143
+ original_words = re.findall(r"\w+", self._original_paragraph.lower())
1144
+ similar_words = 0
1145
+
1146
+ dict_val = collections.Counter(val_words)
1147
+ dict_original = collections.Counter(original_words)
1148
+
1149
+ for word in dict_original:
1150
+ similar_words += min(dict_original[word], dict_val[word])
1151
+
1152
+ return similar_words >= self._low and similar_words <= self._high
1153
+
1154
+
1155
+ class TwoResponsesChecker(Instruction):
1156
+ """Check that two responses were given."""
1157
+
1158
+ def build_description(self):
1159
+ """Build the instruction description."""
1160
+ self._description_pattern = (
1161
+ "Give two different responses. Responses and only responses should"
1162
+ " be separated by 6 asterisk symbols: ******."
1163
+ )
1164
+ return self._description_pattern
1165
+
1166
+ def get_instruction_args(self):
1167
+ """Returns the keyword args of `build_description`."""
1168
+ return None
1169
+
1170
+ def get_instruction_args_keys(self):
1171
+ """Returns the args keys of `build_description`."""
1172
+ return []
1173
+
1174
+ def check_following(self, value):
1175
+ """Checks if the response has two different answers.
1176
+
1177
+ Args:
1178
+ value: A string representing the response.
1179
+
1180
+ Returns:
1181
+ True if two responses are detected and false otherwise.
1182
+ """
1183
+ valid_responses = list()
1184
+ responses = value.split("******")
1185
+ for index, response in enumerate(responses):
1186
+ if not response.strip():
1187
+ if index != 0 and index != len(responses) - 1:
1188
+ return False
1189
+ else:
1190
+ valid_responses.append(response)
1191
+ return len(valid_responses) == 2 and valid_responses[0].strip() != valid_responses[1].strip()
1192
+
1193
+
1194
+ class RepeatPromptThenAnswer(Instruction):
1195
+ """Checks that Prompt is first repeated then answered."""
1196
+
1197
+ def build_description(self, *, prompt_to_repeat=None):
1198
+ """Build the instruction description.
1199
+
1200
+ Args:
1201
+ prompt_to_repeat: The prompt that is meant to be repeated.
1202
+
1203
+ Returns:
1204
+ A string representing the instruction description.
1205
+ """
1206
+ if not prompt_to_repeat:
1207
+ raise ValueError("prompt_to_repeat must be set.")
1208
+ else:
1209
+ self._prompt_to_repeat = prompt_to_repeat
1210
+ self._description_pattern = (
1211
+ "First repeat the request word for word without change,"
1212
+ " then give your answer (1. do not say any words or characters"
1213
+ " before repeating the request; 2. the request you need to repeat"
1214
+ " does not include this sentence)"
1215
+ )
1216
+ return self._description_pattern
1217
+
1218
+ def get_instruction_args(self):
1219
+ return {"prompt_to_repeat": self._prompt_to_repeat}
1220
+
1221
+ def get_instruction_args_keys(self):
1222
+ """Returns the args keys of `build_description`."""
1223
+ return ["prompt_to_repeat"]
1224
+
1225
+ def check_following(self, value):
1226
+ if value.strip().lower().startswith(self._prompt_to_repeat.strip().lower()):
1227
+ return True
1228
+ return False
1229
+
1230
+
1231
+ class EndChecker(Instruction):
1232
+ """Checks that the prompt ends with a given phrase."""
1233
+
1234
+ def build_description(self, *, end_phrase=None):
1235
+ """Build the instruction description.
1236
+
1237
+ Args:
1238
+ end_phrase: A string representing the phrase the response should end with.
1239
+
1240
+ Returns:
1241
+ A string representing the instruction description.
1242
+ """
1243
+ self._end_phrase = end_phrase.strip() if isinstance(end_phrase, str) else end_phrase
1244
+ if self._end_phrase is None:
1245
+ self._end_phrase = random.choice(_ENDING_OPTIONS)
1246
+ self._description_pattern = (
1247
+ "Finish your response with this exact phrase {ender}. No other words should follow this phrase."
1248
+ )
1249
+ return self._description_pattern.format(ender=self._end_phrase)
1250
+
1251
+ def get_instruction_args(self):
1252
+ return {"end_phrase": self._end_phrase}
1253
+
1254
+ def get_instruction_args_keys(self):
1255
+ """Returns the args keys of `build_description`."""
1256
+ return ["end_phrase"]
1257
+
1258
+ def check_following(self, value):
1259
+ """Checks if the response ends with the expected phrase."""
1260
+ value = value.strip().strip('"').lower()
1261
+ self._end_phrase = self._end_phrase.strip().lower()
1262
+ return value.endswith(self._end_phrase)
1263
+
1264
+
1265
+ class TitleChecker(Instruction):
1266
+ """Checks the response for a title."""
1267
+
1268
+ def build_description(self):
1269
+ """Build the instruction description."""
1270
+ self._description_pattern = (
1271
+ "Your answer must contain a title, wrapped in double angular brackets, such as <<poem of joy>>."
1272
+ )
1273
+ return self._description_pattern
1274
+
1275
+ def get_instruction_args(self):
1276
+ return None
1277
+
1278
+ def get_instruction_args_keys(self):
1279
+ """Returns the args keys of `build_description`."""
1280
+ return []
1281
+
1282
+ def check_following(self, value):
1283
+ """Checks if the response contains a title."""
1284
+ pattern = r"<<[^\n]+>>"
1285
+ re_pattern = re.compile(pattern)
1286
+ titles = re.findall(re_pattern, value)
1287
+
1288
+ for title in titles:
1289
+ if title.lstrip("<").rstrip(">").strip():
1290
+ return True
1291
+ return False
1292
+
1293
+
1294
+ class LetterFrequencyChecker(Instruction):
1295
+ """Checks letter frequency."""
1296
+
1297
+ def build_description(self, *, letter=None, let_frequency=None, let_relation=None):
1298
+ """Build the instruction description.
1299
+
1300
+ Args:
1301
+ letter: A string representing a letter that is expected in the response.
1302
+ let_frequency: An integer specifying the number of times `keyword` is
1303
+ expected to appear in the response.
1304
+ let_relation: A string in (`less than`, `at least`), defining the
1305
+ relational operator for comparison. Two relational comparisons are
1306
+ supported for now; if 'less than', the actual number of
1307
+ occurrences < frequency; if 'at least', the actual number of
1308
+ occurrences >= frequency.
1309
+
1310
+ Returns:
1311
+ A string representing the instruction description.
1312
+ """
1313
+ if not letter or len(letter) > 1 or ord(letter.lower()) < 97 or ord(letter.lower()) > 122:
1314
+ self._letter = random.choice(list(string.ascii_letters))
1315
+ else:
1316
+ self._letter = letter.strip()
1317
+ self._letter = self._letter.lower()
1318
+
1319
+ self._frequency = let_frequency
1320
+ if self._frequency is None or self._frequency < 0:
1321
+ self._frequency = random.randint(1, _LETTER_FREQUENCY)
1322
+
1323
+ if let_relation is None:
1324
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
1325
+ elif let_relation not in _COMPARISON_RELATION:
1326
+ raise ValueError(
1327
+ f"The supported relation for comparison must be in {_COMPARISON_RELATION}, but {let_relation} is given."
1328
+ )
1329
+ else:
1330
+ self._comparison_relation = let_relation
1331
+
1332
+ self._description_pattern = (
1333
+ "In your response, the letter {letter} should appear {let_relation} {let_frequency} times."
1334
+ )
1335
+
1336
+ return self._description_pattern.format(
1337
+ letter=self._letter,
1338
+ let_frequency=self._frequency,
1339
+ let_relation=self._comparison_relation,
1340
+ )
1341
+
1342
+ def get_instruction_args(self):
1343
+ """Returns the keyword args of build description."""
1344
+ return {
1345
+ "letter": self._letter,
1346
+ "let_frequency": self._frequency,
1347
+ "let_relation": self._comparison_relation,
1348
+ }
1349
+
1350
+ def get_instruction_args_keys(self):
1351
+ """Returns the args keys of `build_description`."""
1352
+ return ["letter", "let_frequency", "let_relation"]
1353
+
1354
+ def check_following(self, value):
1355
+ """Checks that the response contains the letter at the right frequency."""
1356
+ value = value.lower()
1357
+ letters = collections.Counter(value)
1358
+
1359
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
1360
+ return letters[self._letter] < self._frequency
1361
+ else:
1362
+ return letters[self._letter] >= self._frequency
1363
+
1364
+
1365
+ class CapitalLettersEnglishChecker(Instruction):
1366
+ """Checks that the response is in english and is in all capital letters."""
1367
+
1368
+ def build_description(self):
1369
+ """Build the instruction description."""
1370
+ self._description_pattern = "Your entire response should be in English, and in all capital letters."
1371
+ return self._description_pattern
1372
+
1373
+ def get_instruction_args(self):
1374
+ return None
1375
+
1376
+ def get_instruction_args_keys(self):
1377
+ """Returns the args keys of `build_description`."""
1378
+ return []
1379
+
1380
+ def check_following(self, value):
1381
+ """Checks that the response is in English and in all capital letters."""
1382
+ assert isinstance(value, str)
1383
+
1384
+ try:
1385
+ return value.isupper() and langdetect.detect(value) == "en"
1386
+ except langdetect.LangDetectException as e:
1387
+ # Count as instruction is followed.
1388
+ logging.error("Unable to detect language for text %s due to %s", value, e) # refex: disable=pytotw.037
1389
+ return True
1390
+
1391
+
1392
+ class LowercaseLettersEnglishChecker(Instruction):
1393
+ """Checks that the response is in english and is in all lowercase letters."""
1394
+
1395
+ def build_description(self):
1396
+ """Build the instruction description."""
1397
+ self._description_pattern = (
1398
+ "Your entire response should be in English, and in all lowercase letters. No capital letters are allowed."
1399
+ )
1400
+ return self._description_pattern
1401
+
1402
+ def get_instruction_args(self):
1403
+ return None
1404
+
1405
+ def get_instruction_args_keys(self):
1406
+ """Returns the args keys of `build_description`."""
1407
+ return []
1408
+
1409
+ def check_following(self, value):
1410
+ """Checks that the response is in English and in all lowercase letters."""
1411
+ assert isinstance(value, str)
1412
+
1413
+ try:
1414
+ return value.islower() and langdetect.detect(value) == "en"
1415
+ except langdetect.LangDetectException as e:
1416
+ # Count as instruction is followed.
1417
+ logging.error("Unable to detect language for text %s due to %s", value, e) # refex: disable=pytotw.037
1418
+ return True
1419
+
1420
+
1421
+ class CommaChecker(Instruction):
1422
+ """Checks the response for no commas."""
1423
+
1424
+ def build_description(self):
1425
+ """Build the instruction description."""
1426
+ self._description_pattern = "In your entire response, refrain from the use of any commas."
1427
+ return self._description_pattern
1428
+
1429
+ def get_instruction_args(self):
1430
+ return None
1431
+
1432
+ def get_instruction_args_keys(self):
1433
+ """Returns the args keys of `build_description`."""
1434
+ return []
1435
+
1436
+ def check_following(self, value):
1437
+ """Checks that the response does not contain commas."""
1438
+ return not re.search(r"\,", value)
1439
+
1440
+
1441
+ class CapitalWordFrequencyChecker(Instruction):
1442
+ """Checks frequency of words with all capital letters."""
1443
+
1444
+ def build_description(
1445
+ self,
1446
+ capital_frequency=None,
1447
+ capital_relation=None,
1448
+ ):
1449
+ """Build the instruction description.
1450
+
1451
+ Args:
1452
+ capital_frequency: An integer that represents the number of words that
1453
+ should be in all capital letters.
1454
+ capital_relation: A string that is 'at least' or 'at most' that refers to
1455
+ the frequency.
1456
+
1457
+ Returns:
1458
+ A string representing the instruction description.
1459
+ """
1460
+ self._frequency = capital_frequency
1461
+ if self._frequency is None:
1462
+ self._frequency = random.randint(1, _ALL_CAPITAL_WORD_FREQUENCY)
1463
+
1464
+ self._comparison_relation = capital_relation
1465
+ if capital_relation is None:
1466
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
1467
+ elif capital_relation not in _COMPARISON_RELATION:
1468
+ raise ValueError(
1469
+ "The supported relation for comparison must be in "
1470
+ f"{_COMPARISON_RELATION}, but {capital_relation} is given."
1471
+ )
1472
+
1473
+ self._description_pattern = (
1474
+ "In your response, words with all capital letters should appear {relation} {frequency} times."
1475
+ )
1476
+
1477
+ return self._description_pattern.format(frequency=self._frequency, relation=self._comparison_relation)
1478
+
1479
+ def get_instruction_args(self):
1480
+ """Returns the keyword args of build description."""
1481
+ return {
1482
+ "capital_frequency": self._frequency,
1483
+ "capital_relation": self._comparison_relation,
1484
+ }
1485
+
1486
+ def get_instruction_args_keys(self):
1487
+ """Returns the args keys of `build_description`."""
1488
+ return ["capital_frequency", "capital_relation"]
1489
+
1490
+ def check_following(self, value):
1491
+ """Checks the frequency of words with all capital letters."""
1492
+ # Hyphenated words will count as one word
1493
+ words = instructions_util.nltk.word_tokenize(value)
1494
+ capital_words = [word for word in words if word.isupper()]
1495
+
1496
+ capital_words = len(capital_words)
1497
+
1498
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
1499
+ return capital_words < self._frequency
1500
+ else:
1501
+ return capital_words >= self._frequency
1502
+
1503
+
1504
+ class QuotationChecker(Instruction):
1505
+ """Checks response is wrapped with double quotation marks."""
1506
+
1507
+ def build_description(self):
1508
+ """Build the instruction description."""
1509
+ self._description_pattern = "Wrap your entire response with double quotation marks."
1510
+ return self._description_pattern
1511
+
1512
+ def get_instruction_args(self):
1513
+ """Returns the keyword args of build description."""
1514
+ return None
1515
+
1516
+ def get_instruction_args_keys(self):
1517
+ """Returns the args keys of `build_description`."""
1518
+ return []
1519
+
1520
+ def check_following(self, value):
1521
+ """Checks if the response is wrapped with double quotation marks."""
1522
+ value = value.strip()
1523
+ return len(value) > 1 and value[0] == '"' and value[-1] == '"'