File size: 21,182 Bytes
8014d08 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 |
import re
import string
import random
from typing import Optional, Tuple, List, Dict
from nltk.stem import PorterStemmer
PSTEMMER = PorterStemmer()
GAME_RULE_PROMPTS = [
"""Play the game of Collabrative Rational Speech Act Game. In this game, there are two players, a speaker and a listener.
At the beginning, the speaker is assigned a target object, with which the listener is not informed. The task of the speaker is to guide the listener to guess the target object, then they win the game. However, the speaker is only allowed to give one feature per turn.
At the same time, the listener tries to figure out the target object and give the possible target referent objects at each turn. The listener can give more than one possible target referent object sets at each turn. If the listener identifies the target object, he can say "I know the target object! It is `target object`!".
At each turn, the speaker should try to give a feature of the target object which provides the listener with the most information, and the listener would update the possible target referent objects from the previous turn.
Remember, the listener can only update his referent set from the previous turn's guess, he cannot add new referents.
The less turns they take to guess the target object, the higher the score they get.
""",
"""Engage in the collaborative challenge of Rational Speech Act Game, featuring two participants: one takes on the role of the speaker, while the other serves as the listener.
Initially, the speaker is secretly assigned a target object, which remains unknown to the listener. The speaker's objective is to strategically guide the listener toward identifying the target object, thereby securing victory. However, there's a constraint: the speaker may only provide one feature per turn.
Simultaneously, the listener's mission is to deduce the target object and present possible target referent objects at each turn. The listener has the flexibility to offer multiple possible target referent object sets during their turn. If the listener identifies the target object, they can declare "I know the target object! It is `target object`!".
During each turn, the speaker should aim to provide a feature of the target object that maximizes the information available to the listener, while the listener updates their possible target referent objects based on the previous turn's information.
Remember, the listener can only update their referent set from the previous turn's guess; they cannot add new referents.
The scoring system rewards efficiency: fewer turns required to guess the target object results in higher scores.
""",
"""Dive into the strategic collaboration known as Rational Speech Act Game, where two players assume distinct roles: the speaker and the listener.
To commence the game, the speaker receives a target object in secret, while the listener remains unaware of this object. The speaker's challenge is to effectively guide the listener toward correctly identifying the target object, which would result in a win. However, there's a limitation: the speaker can only share one feature per turn.
Concurrently, the listener embarks on a quest to determine the target object and must present possible target referent objects at each turn. The listener enjoys the advantage of being able to propose multiple possible target referent object sets during their turn. If the listener identifies the target object, they can proclaim "I know the target object! It is `target object`!".
At each turn, the speaker should strategically select a feature of the target object that provides the listener with maximum informational value, while the listener refines their possible target referent objects based on the previous turn's revelations.
Remember, the listener can only update their referent set from the previous turn's guess; they cannot add new referents.
The scoring mechanism emphasizes efficiency: achieving the target object identification in fewer turns yields higher scores.
""",
"""Step into the cooperative challenge of Rational Speech Act Game, a game designed for two players: one acting as the speaker, the other as the listener.
In the opening phase, the speaker is discreetly given a target object, which is kept hidden from the listener. The speaker's goal is to successfully lead the listener to identify the target object, thereby claiming victory. However, there's a rule: the speaker is restricted to providing only one feature per turn.
At the same time, the listener's task is to figure out the target object and present possible target referent objects at each turn. The listener has the liberty to suggest multiple possible target referent object sets during their turn. If the listener identifies the target object, they can announce "I know the target object! It is `target object`!".
During each turn, the speaker should carefully choose a feature of the target object that delivers the most valuable information to the listener, while the listener adjusts their possible target referent objects based on the previous turn's insights.
Remember, the listener can only update their referent set from the previous turn's guess; they cannot add new referents.
The scoring system prioritizes efficiency: the fewer turns taken to identify the target object, the higher the score achieved.
""",
"""Immerse yourself in the collaborative strategy game called Rational Speech Act Game, featuring two distinct roles: the speaker and the listener.
As the game begins, the speaker is covertly assigned a target object, which remains a mystery to the listener. The speaker's mission is to skillfully guide the listener toward correctly identifying the target object, which would secure a win. However, there's a restriction: the speaker may only offer one feature per turn.
Meanwhile, the listener is engaged in a process of deduction, attempting to determine the target object and presenting possible target referent objects at each turn. The listener benefits from the ability to suggest multiple possible target referent object sets during their turn. If the listener identifies the target object, they can state "I know the target object! It is `target object`!".
At each turn, the speaker should strategically provide a feature of the target object that maximizes the informational benefit for the listener, while the listener updates their possible target referent objects based on the previous turn's information.
Remember, the listener can only update their referent set from the previous turn's guess; they cannot add new referents.
The scoring framework rewards efficiency: fewer turns required to identify the target object results in higher scores.
""",
"""Dive into the collaborative challenge known as Rational Speech Act Game, where two players take on specific roles: the speaker and the listener.
The speaker starts the game with a secret target object assignment, while the listener remains in the dark about this object. The speaker's objective is to effectively guide the listener toward identifying the target object, thereby achieving victory. However, there's a constraint: the speaker can only provide one feature per turn.
Concurrently, the listener's challenge is to deduce the target object and present possible target referent objects at each turn. The listener enjoys the flexibility of being able to suggest multiple possible target referent object sets during their turn. If the listener identifies the target object, they can express "I know the target object! It is `target object`!".
During each turn, the speaker should aim to provide a feature of the target object that offers the listener the most valuable information, while the listener refines their possible target referent objects based on the previous turn's revelations.
Remember, the listener can only update their referent set from the previous turn's guess; they cannot add new referents.
The scoring mechanism emphasizes efficiency: achieving target object identification in fewer turns yields higher scores.
""",
"""Step into the strategic collaboration called Rational Speech Act Game, where the roles of speaker and listener are central to the gameplay.
The speaker embarks on this journey with a secretly assigned target object, while the listener begins unaware of this object. The speaker's challenge is to successfully guide the listener toward identifying the target object, which would result in a win. However, there's a limitation: the speaker is only permitted to share one feature per turn.
On the other side, the listener's mission is to figure out the target object and present possible target referent objects at each turn. The listener has the advantage of being able to propose multiple possible target referent object sets during their turn. If the listener identifies the target object, they can reveal "I know the target object! It is `target object`!".
At each turn, the speaker should strategically select a feature of the target object that provides the listener with maximum informational value, while the listener updates their possible target referent objects based on the previous turn's insights.
Remember, the listener can only update their referent set from the previous turn's guess; they cannot add new referents.
The scoring system prioritizes efficiency: fewer turns taken to identify the target object results in higher scores.
""",
"""Embark on the collaborative challenge of Rational Speech Act Game, where players assume the roles of either speaker or listener.
The speaker enters the game with a covertly assigned target object, while the listener starts without knowledge of this object. The speaker's goal is to effectively guide the listener toward identifying the target object, thereby securing victory. However, there's a rule: the speaker may only provide one feature per turn.
Simultaneously, the listener's task is to deduce the target object and present possible target referent objects at each turn. The listener benefits from the ability to suggest multiple possible target referent object sets during their turn. If the listener identifies the target object, they can declare "I know the target object! It is `target object`!".
During each turn, the speaker should carefully choose a feature of the target object that delivers the most valuable information to the listener, while the listener adjusts their possible target referent objects based on the previous turn's information.
Remember, the listener can only update their referent set from the previous turn's guess; they cannot add new referents.
The scoring framework rewards efficiency: the fewer turns required to identify the target object, the higher the score achieved.
""",
]
INSTRUCT_PROMPTS = {
"speaker": """\n\n### Instruction: You are the pragmatic rational speaker. The target object is `{target}` and the object list is '{object_list}'. Provide your response including the object feature.\n\n### Response:""",
"listener": """\n\n### Instruction: Your are the pragmatic rational listener. The object list is '{object_list}'. Provide your infered target object or the possible target object sets.\n\n### Response:""",
}
PLAYER_INSTRUCT_PROMPTS = {
"speaker": "You are the pragmatic rational speaker. The target object is `{target}` and the object list is '{object_list}'. Provide your response including the object feature.",
"listener": "Your are the pragmatic rational listener. The object list is '{object_list}'. Provide your infered target object or the possible target object sets.",
}
ROLES = ["speaker", "listener"]
PREDICT_TEMP = r"i know the target object"
def calculate_reward(turn, golden_turn):
if turn <= golden_turn:
return 1
else:
return 0
def get_object_list(formatted_str):
"""Reverse the item_string function to extract the original list of items"""
# If the string is empty, return empty list
if not formatted_str:
return []
# Remove surrounding brackets/parentheses/braces if present
if formatted_str.startswith("[") and formatted_str.endswith("]"):
formatted_str = formatted_str[1:-1].strip()
elif formatted_str.startswith("(") and formatted_str.endswith(")"):
formatted_str = formatted_str[1:-1].strip()
elif formatted_str.startswith("{") and formatted_str.endswith("}"):
formatted_str = formatted_str[1:-1].strip()
# Handle different formats
if ", and " in formatted_str: # Oxford comma format
parts = formatted_str.split(", and ")
if len(parts) > 1:
return [item.strip() for item in parts[0].split(", ")] + [parts[1].strip()]
elif " and " in formatted_str and ", " in formatted_str: # No Oxford comma
parts = formatted_str.split(", ")
last_part = parts[-1]
if " and " in last_part:
last_items = last_part.split(" and ")
return [item.strip() for item in parts[:-1]] + [
item.strip() for item in last_items
]
elif " and " in formatted_str: # "and" separated format
return [item.strip() for item in formatted_str.split(" and ")]
elif ", " in formatted_str: # Comma separated format
return [item.strip() for item in formatted_str.split(", ")]
# If none of the above patterns match, return the string as a single-item list
return [formatted_str.strip()]
def get_derivative_targets(object_list, random_choice=True):
"""Format a list of items in various natural ways"""
# Randomly choose from different formats
format_choices = {
"comma": lambda x: ", ".join(x),
"bracket": lambda x: "[" + ", ".join(x) + "]",
"parenthesis": lambda x: "(" + ", ".join(x) + ")",
"curly": lambda x: "{" + ", ".join(x) + "}",
"oxford_comma": lambda x: ", ".join(x[:-1]) + ", and " + x[-1],
"and_comma": lambda x: " and ".join(x[:-1]) + ", and " + x[-1],
"no_oxford_comma": lambda x: ", ".join(x[:-1]) + " and " + x[-1],
"and_separated": lambda x: " and ".join(x),
}
if random_choice:
format = random.choice(list(format_choices.keys()))
return format_choices[format](object_list)
else:
return [func(object_list) for format, func in format_choices.items()]
def has_target_object(content: str, target_object: list):
derivative_objects = get_derivative_targets(target_object, random_choice=False)
return any([object in content.lower() for object in derivative_objects])
def is_prediction(content: str, target_object: list):
if re.search(PREDICT_TEMP, content.lower()):
return True
else:
return False
def is_correct_prediction(content: str, target_object: list):
derivative_objects = get_derivative_targets(target_object, random_choice=False)
if any(object in content.lower() for object in derivative_objects):
return True
# Remove all punctuation from content except '.', '!', and ','
content = ''.join([c for c in content if not (c in set(string.punctuation) and c not in {'.', '!', ','})])
for feature in target_object:
if feature in content.lower():
continue
else:
# Use a custom stemmer to handle cases like "crispy" -> "crisp"
def custom_stem(word):
if word.endswith("y") and len(word) > 3:
return PSTEMMER.stem(word[:-1])
return PSTEMMER.stem(word)
feature_stem = custom_stem(feature.lower())
content_words = [word for word in content.lower().split()]
content_stems = [custom_stem(word) for word in content_words]
if not any(feature_stem == stem or feature_stem in stem for stem in content_stems):
return False
return True
# derivative_objects = get_derivative_targets(target_object, random_choice=False)
# predict_regex = [PREDICT_TEMP + object for object in derivative_objects]
# if any([re.search(temp, content.lower()) for temp in predict_regex]):
# return True
# else:
# return False
def get_game_outcome(history: List[Dict[str, str]], target_object: list, min_turns: int):
history_length = 0
for i, item in enumerate(history):
history_length += 1
if item["role"] == "listener":
if is_prediction(item["content"], target_object):
if is_correct_prediction(item["content"], target_object):
return "game wins", history_length
else:
return "game over", history_length
elif not has_target_object(item["content"], target_object) and i == len(history) - 1:
return "listener does not infer the target object", history_length
else:
if is_prediction(item["content"], target_object):
return "speaker breaks the rules", history_length
return "game over", history_length
def convert_game_history_to_query(history, target, object_list):
GAME_RULE_PROMPT = GAME_RULE_PROMPTS[0]
history_str = ""
for i, message in enumerate(history):
history_str += "\n - {}: {}".format(
message["role"], message["content"])
if len(history) == 0:
query = (
GAME_RULE_PROMPT +
+ "The game is just initialized."
)
next_player = ROLES[0]
else:
query = (
GAME_RULE_PROMPT
+ "\n### Game History:"
+ history_str
)
if history[-1]["role"] == ROLES[0]:
next_player = ROLES[1]
else:
next_player = ROLES[0]
query += INSTRUCT_PROMPTS[next_player].format(
target=get_derivative_targets(target),
object_list=get_derivative_targets(object_list),
)
return query
def randomly_convert_game_history_to_query(history, target, object_list, **kwargs):
if "random_seed" in kwargs:
random.seed(kwargs["random_seed"])
if len(history) == 0:
next_player = ROLES[0]
else:
if history[-1]["role"] == ROLES[0]:
next_player = ROLES[1]
else:
next_player = ROLES[0]
dialog_prefix = "\n" + random.choice(
["\n - ", "\n### ", "\n## ", "\n# ", "\n *** ", "\n **", "\n\n"]
)
answer_str, question_str = random.choice(
[
(next_player, ROLES[1] if next_player == ROLES[0] else ROLES[0]),
("Assistant", "Human"),
("Answer", "Question"),
("Response", "Query"),
("A", "Q"),
]
)
player_prefix = {
ROLES[0]: answer_str if next_player == ROLES[0] else question_str,
ROLES[1]: answer_str if next_player == ROLES[1] else question_str,
}
history_str = ""
for i, message in enumerate(history):
history_str += "{}{}: {}".format(
dialog_prefix, player_prefix[message["role"]], message["content"]
)
prompt_type = random.choice(["chat", "chat_inverse", "alpaca"])
system_prefix = random.choice(["Rules", "Game Rule", "System"])
system_prompt = random.choice(GAME_RULE_PROMPTS)
if isinstance(object_list, str):
objects_str = object_list
else:
objects_str = get_derivative_targets(object_list)
if "chat" in prompt_type:
system_prompt += "\n\n" + PLAYER_INSTRUCT_PROMPTS[next_player].format(
target=get_derivative_targets(target),
object_list=objects_str,
)
if len(history) == 0:
history_str = ""
system_prompt += "The game is just initialized. "
system_str = f"{dialog_prefix}{system_prefix}: {system_prompt}"
if "inverse" in prompt_type:
query = (
history_str
+ system_str
+ dialog_prefix
+ player_prefix[next_player]
+ ": "
)
else:
query = (
system_str
+ history_str
+ dialog_prefix
+ player_prefix[next_player]
+ ": "
)
elif prompt_type == "alpaca":
if random.uniform(0, 1) < 0.2:
system_prompt = system_prefix + ": " + system_prompt
if len(history) == 0:
query = system_prompt + "The game is just initialized. "
else:
query = (
system_prompt + dialog_prefix + "Game History:" + history_str + "\n\n"
)
if random.uniform(0, 1) < 0.2:
query += (
PLAYER_INSTRUCT_PROMPTS[next_player].format(
target=target,
object_list=objects_str,
)[:-1]
+ ": "
)
else:
query += (
PLAYER_INSTRUCT_PROMPTS[next_player].format(
target=target,
object_list=objects_str,
)
+ dialog_prefix
+ player_prefix[next_player]
+ ": "
)
return query
|