|
|
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 not formatted_str: |
|
|
return [] |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
if ", and " in formatted_str: |
|
|
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: |
|
|
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: |
|
|
return [item.strip() for item in formatted_str.split(" and ")] |
|
|
elif ", " in formatted_str: |
|
|
return [item.strip() for item in formatted_str.split(", ")] |
|
|
|
|
|
|
|
|
return [formatted_str.strip()] |
|
|
|
|
|
|
|
|
def get_derivative_targets(object_list, random_choice=True): |
|
|
"""Format a list of items in various natural ways""" |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
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: |
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
|