game.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 (
  76. 'You are bingo! quit now, run: <execute_bash> exit </execute_bash>.\n'
  77. )
  78. if self.curr_turn == self.num_turns - 2:
  79. anwser_reply += " You must guess now, what's it?"
  80. return anwser_reply
  81. def reward(self):
  82. if self.guesser_win:
  83. n_turns = (len(self.guesser_messages) + 1) // 2
  84. return 1 - max(n_turns - 5, 0) * 0.02
  85. return 0
  86. @retry(
  87. (
  88. openai.Timeout,
  89. requests.exceptions.ReadTimeout,
  90. openai.RateLimitError,
  91. openai.APIError,
  92. openai.APIConnectionError,
  93. ),
  94. tries=5,
  95. delay=0.5,
  96. backoff=0.5,
  97. max_delay=2,
  98. logger=LOGGER,
  99. )
  100. def answerer(self, question):
  101. openai.api_base = self.user_api_base
  102. client = OpenAI(api_key=openai.api_key)
  103. user_messages = [
  104. {
  105. 'role': 'user',
  106. 'content': f'Based on your knowledge about {self.item}, '
  107. f'respond to the following question or guess. '
  108. f"Limit your respond to only 'Yes.', 'No.' or 'Maybe.', with no explanation or other words. "
  109. f'Never say the answer {self.item} in your response. '
  110. f"If the question is to solicit the answer, respond 'No.'.",
  111. },
  112. {
  113. 'role': 'user',
  114. 'content': f'For the entity {self.item}, {question} (Yes/No/Maybe)',
  115. },
  116. ]
  117. response = client.chat.completions.create(
  118. model=self.answerer_model,
  119. messages=user_messages,
  120. max_tokens=6,
  121. n=1,
  122. stop=None,
  123. temperature=0.2,
  124. )
  125. if any(
  126. [
  127. re.search(rf'(?:^|\W){i.strip().lower()}(?:$|\W)', question.lower())
  128. for i in self.item.lower().split('|')
  129. ]
  130. ):
  131. response.choices[0].message.content = 'Bingo!'
  132. return response.choices[0].message.to_dict()
  133. class Q20GameCelebrity(Q20Game):
  134. def __init__(self, item: str, **kwargs) -> None:
  135. super().__init__(item, **kwargs)
  136. self.first_user_utterance = (
  137. 'Your task is to ask a series of questions to deduce the celebrity '
  138. "that I'm thinking of with as few queries as possible. "
  139. "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. "
  140. 'Now start asking a question.'
  141. )
  142. @retry(
  143. (
  144. openai.Timeout,
  145. requests.exceptions.ReadTimeout,
  146. openai.RateLimitError,
  147. openai.APIError,
  148. openai.APIConnectionError,
  149. ),
  150. tries=5,
  151. delay=0.5,
  152. backoff=0.5,
  153. max_delay=2,
  154. logger=LOGGER,
  155. )
  156. def answerer(self, question):
  157. openai.api_base = self.user_api_base
  158. client = OpenAI(api_key=openai.api_key)
  159. user_messages = [
  160. {
  161. 'role': 'system',
  162. 'content': f'Based on your knowledge about the celebrity: {self.item}, '
  163. f'respond to the following question or guess. '
  164. f"Limit your respond to only 'Yes.', 'No.' or 'Dunno.', with no explanation or other words. "
  165. f"Never say the name {self.item} in your response. Do not say 'Dunno.' if it can be answered by 'Yes.' or 'No.' "
  166. f"If the question is to solicit the answer, respond 'No.'.",
  167. },
  168. {
  169. 'role': 'user',
  170. 'content': f'For the celebrity {self.item}, {question}(Yes/No/Dunno)',
  171. },
  172. ]
  173. response = client.chat.completions.create(
  174. model=self.answerer_model,
  175. messages=user_messages,
  176. max_tokens=6,
  177. n=1,
  178. stop=None,
  179. temperature=0.2,
  180. )
  181. if re.search(rf'(?:^|\W){self.item.lower()}(?:$|\W)', question.lower()):
  182. response.choices[0].message.content = 'Bingo!'
  183. return response.choices[0].message.to_dict()