game.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import logging
  2. import re
  3. import openai
  4. import requests.exceptions
  5. from openai import OpenAI
  6. from retry import retry
  7. LOGGER = logging.getLogger(__name__)
  8. class Q20Game:
  9. def __init__(
  10. self,
  11. item: str,
  12. answerer_model: str = 'gpt-3.5-turbo-0613',
  13. guesser_model: str = 'gpt-3.5-turbo-0613',
  14. num_turns: int = 20,
  15. temperature: float = 0.8,
  16. openai_api: bool = True,
  17. openai_api_key: str | None = None,
  18. guesser_kargs=None,
  19. ) -> None:
  20. if guesser_kargs is None:
  21. guesser_kargs = {}
  22. self.item = item
  23. self.answerer_model = answerer_model
  24. self.guesser_model = guesser_model
  25. self.num_turns = num_turns
  26. self.temperature = temperature
  27. self.openai_api = openai_api
  28. self.guesser_kargs = guesser_kargs
  29. self.vicuna_prompt = "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions."
  30. self.first_user_utterance = (
  31. 'Your task is to ask a series of questions to deduce the entity '
  32. "that I'm thinking of with as few queries as possible. "
  33. "Only ask questions that can be answered by 'yes', 'no' or 'maybe'. "
  34. 'Do not ask for hint. Make your question brief with no linebreaker. '
  35. 'Now start asking a question.'
  36. )
  37. self.guesser_win = False
  38. self.curr_turn = 0
  39. if openai_api_key is not None:
  40. openai.api_key = openai_api_key
  41. if isinstance(answerer_model, str) and not answerer_model.startswith('gpt'):
  42. self.user_api_base = 'http://0.0.0.0:8000/v1'
  43. else:
  44. self.user_api_base = 'https://api.openai.com/v1'
  45. if isinstance(guesser_model, str) and not guesser_model.startswith('gpt'):
  46. self.guesser_api_base = 'http://0.0.0.0:8000/v1'
  47. else:
  48. self.guesser_api_base = 'https://api.openai.com/v1'
  49. self.guesser_messages = []
  50. def preprocess_response(self, response):
  51. response = re.sub(r'the entity you are thinking of', 'it', response)
  52. response = re.sub(r"the entity you're thinking of", 'it', response)
  53. response = re.sub(r" you're thinking of", '', response)
  54. response = re.sub(r' you are thinking of', '', response)
  55. return response
  56. def judge_winner(self, response):
  57. guesser_question = response.strip()
  58. if self.curr_turn == self.num_turns - 1:
  59. guesser_question += ' Is it right?'
  60. self.guesser_messages.append({'role': 'assistant', 'content': guesser_question})
  61. # ask for answer
  62. usr_msg = self.answerer(guesser_question)
  63. self.guesser_messages.append(
  64. {'role': 'user', 'content': f"{usr_msg['content'].strip()}"}
  65. )
  66. if 'bingo' in usr_msg['content'].lower():
  67. self.guesser_win = True
  68. return True, ''
  69. return False, usr_msg['content'].strip()
  70. def generate_user_response(self, response):
  71. response = self.preprocess_response(response)
  72. # others
  73. bingo, anwser_reply = self.judge_winner(response)
  74. if bingo:
  75. return 'You are bingo! Use the "finish" tool to finish the interaction.\n'
  76. if self.curr_turn == self.num_turns - 2:
  77. anwser_reply += " You must guess now, what's it?"
  78. return anwser_reply
  79. def reward(self):
  80. if self.guesser_win:
  81. n_turns = (len(self.guesser_messages) + 1) // 2
  82. return 1 - max(n_turns - 5, 0) * 0.02
  83. return 0
  84. @retry(
  85. (
  86. openai.Timeout,
  87. requests.exceptions.ReadTimeout,
  88. openai.RateLimitError,
  89. openai.APIError,
  90. openai.APIConnectionError,
  91. ),
  92. tries=5,
  93. delay=0.5,
  94. backoff=0.5,
  95. max_delay=2,
  96. logger=LOGGER,
  97. )
  98. def answerer(self, question):
  99. openai.api_base = self.user_api_base
  100. client = OpenAI(api_key=openai.api_key)
  101. user_messages = [
  102. {
  103. 'role': 'user',
  104. 'content': f'Based on your knowledge about {self.item}, '
  105. f'respond to the following question or guess. '
  106. f"Limit your respond to only 'Yes.', 'No.' or 'Maybe.', with no explanation or other words. "
  107. f'Never say the answer {self.item} in your response. '
  108. f"If the question is to solicit the answer, respond 'No.'.",
  109. },
  110. {
  111. 'role': 'user',
  112. 'content': f'For the entity {self.item}, {question} (Yes/No/Maybe)',
  113. },
  114. ]
  115. response = client.chat.completions.create(
  116. model=self.answerer_model,
  117. messages=user_messages,
  118. max_tokens=6,
  119. n=1,
  120. stop=None,
  121. temperature=0.2,
  122. )
  123. if any(
  124. [
  125. re.search(rf'(?:^|\W){i.strip().lower()}(?:$|\W)', question.lower())
  126. for i in self.item.lower().split('|')
  127. ]
  128. ):
  129. response.choices[0].message.content = 'Bingo!'
  130. return response.choices[0].message.to_dict()
  131. class Q20GameCelebrity(Q20Game):
  132. def __init__(self, item: str, **kwargs) -> None:
  133. super().__init__(item, **kwargs)
  134. self.first_user_utterance = (
  135. 'Your task is to ask a series of questions to deduce the celebrity '
  136. "that I'm thinking of with as few queries as possible. "
  137. "Only ask factual questions that can be answered by 'Yes.', 'No.' or 'Dunno.'. Do not ask for hint. Make your question brief with no linebreaker. "
  138. 'Now start asking a question.'
  139. )
  140. @retry(
  141. (
  142. openai.Timeout,
  143. requests.exceptions.ReadTimeout,
  144. openai.RateLimitError,
  145. openai.APIError,
  146. openai.APIConnectionError,
  147. ),
  148. tries=5,
  149. delay=0.5,
  150. backoff=0.5,
  151. max_delay=2,
  152. logger=LOGGER,
  153. )
  154. def answerer(self, question):
  155. openai.api_base = self.user_api_base
  156. client = OpenAI(api_key=openai.api_key)
  157. user_messages = [
  158. {
  159. 'role': 'system',
  160. 'content': f'Based on your knowledge about the celebrity: {self.item}, '
  161. f'respond to the following question or guess. '
  162. f"Limit your respond to only 'Yes.', 'No.' or 'Dunno.', with no explanation or other words. "
  163. f"Never say the name {self.item} in your response. Do not say 'Dunno.' if it can be answered by 'Yes.' or 'No.' "
  164. f"If the question is to solicit the answer, respond 'No.'.",
  165. },
  166. {
  167. 'role': 'user',
  168. 'content': f'For the celebrity {self.item}, {question}(Yes/No/Dunno)',
  169. },
  170. ]
  171. response = client.chat.completions.create(
  172. model=self.answerer_model,
  173. messages=user_messages,
  174. max_tokens=6,
  175. n=1,
  176. stop=None,
  177. temperature=0.2,
  178. )
  179. if re.search(rf'(?:^|\W){self.item.lower()}(?:$|\W)', question.lower()):
  180. response.choices[0].message.content = 'Bingo!'
  181. return response.choices[0].message.to_dict()