You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

claude_ai_bot.py 8.6KB

1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
1 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import re
  2. import time
  3. import json
  4. import uuid
  5. from curl_cffi import requests
  6. from bot.bot import Bot
  7. from bot.chatgpt.chat_gpt_session import ChatGPTSession
  8. from bot.openai.open_ai_image import OpenAIImage
  9. from bot.session_manager import SessionManager
  10. from bridge.context import Context, ContextType
  11. from bridge.reply import Reply, ReplyType
  12. from common.log import logger
  13. from config import conf
  14. class ClaudeAIBot(Bot, OpenAIImage):
  15. def __init__(self):
  16. super().__init__()
  17. self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "gpt-3.5-turbo")
  18. self.claude_api_cookie = conf().get("claude_api_cookie")
  19. self.proxy = conf().get("proxy")
  20. if self.proxy:
  21. self.proxies = {
  22. "http": self.proxy,
  23. "https": self.proxy
  24. }
  25. else:
  26. self.proxies = None
  27. self.org_uuid = self.get_organization_id()
  28. self.con_uuid = None
  29. self.get_uuid()
  30. def generate_uuid(self):
  31. random_uuid = uuid.uuid4()
  32. random_uuid_str = str(random_uuid)
  33. formatted_uuid = f"{random_uuid_str[0:8]}-{random_uuid_str[9:13]}-{random_uuid_str[14:18]}-{random_uuid_str[19:23]}-{random_uuid_str[24:]}"
  34. return formatted_uuid
  35. def get_uuid(self):
  36. if conf().get("claude_uuid") != None:
  37. self.con_uuid = conf().get("claude_uuid")
  38. else:
  39. self.con_uuid = self.generate_uuid()
  40. self.create_new_chat()
  41. def get_organization_id(self):
  42. url = "https://claude.ai/api/organizations"
  43. headers = {
  44. 'User-Agent':
  45. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
  46. 'Accept-Language': 'en-US,en;q=0.5',
  47. 'Referer': 'https://claude.ai/chats',
  48. 'Content-Type': 'application/json',
  49. 'Sec-Fetch-Dest': 'empty',
  50. 'Sec-Fetch-Mode': 'cors',
  51. 'Sec-Fetch-Site': 'same-origin',
  52. 'Connection': 'keep-alive',
  53. 'Cookie': f'{self.claude_api_cookie}'
  54. }
  55. response = requests.get(url, headers=headers,impersonate="chrome110",proxies=self.proxies)
  56. res = json.loads(response.text)
  57. uuid = res[0]['uuid']
  58. return uuid
  59. def reply(self, query, context: Context = None) -> Reply:
  60. if context.type == ContextType.TEXT:
  61. return self._chat(query, context)
  62. elif context.type == ContextType.IMAGE_CREATE:
  63. ok, res = self.create_img(query, 0)
  64. if ok:
  65. reply = Reply(ReplyType.IMAGE_URL, res)
  66. else:
  67. reply = Reply(ReplyType.ERROR, res)
  68. return reply
  69. else:
  70. reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type))
  71. return reply
  72. def get_organization_id(self):
  73. url = "https://claude.ai/api/organizations"
  74. headers = {
  75. 'User-Agent':
  76. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
  77. 'Accept-Language': 'en-US,en;q=0.5',
  78. 'Referer': 'https://claude.ai/chats',
  79. 'Content-Type': 'application/json',
  80. 'Sec-Fetch-Dest': 'empty',
  81. 'Sec-Fetch-Mode': 'cors',
  82. 'Sec-Fetch-Site': 'same-origin',
  83. 'Connection': 'keep-alive',
  84. 'Cookie': f'{self.claude_api_cookie}'
  85. }
  86. try:
  87. response = requests.get(url, headers=headers,impersonate="chrome110",proxies =self.proxies )
  88. res = json.loads(response.text)
  89. uuid = res[0]['uuid']
  90. except:
  91. print(response.text)
  92. return uuid
  93. def create_new_chat(self):
  94. url = f"https://claude.ai/api/organizations/{self.org_uuid}/chat_conversations"
  95. payload = json.dumps({"uuid": self.con_uuid, "name": ""})
  96. headers = {
  97. 'User-Agent':
  98. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
  99. 'Accept-Language': 'en-US,en;q=0.5',
  100. 'Referer': 'https://claude.ai/chats',
  101. 'Content-Type': 'application/json',
  102. 'Origin': 'https://claude.ai',
  103. 'DNT': '1',
  104. 'Connection': 'keep-alive',
  105. 'Cookie': self.claude_api_cookie,
  106. 'Sec-Fetch-Dest': 'empty',
  107. 'Sec-Fetch-Mode': 'cors',
  108. 'Sec-Fetch-Site': 'same-origin',
  109. 'TE': 'trailers'
  110. }
  111. response = requests.post( url, headers=headers, data=payload,impersonate="chrome110", proxies= self.proxies)
  112. # Returns JSON of the newly created conversation information
  113. return response.json()
  114. def _chat(self, query, context, retry_count=0) -> Reply:
  115. """
  116. 发起对话请求
  117. :param query: 请求提示词
  118. :param context: 对话上下文
  119. :param retry_count: 当前递归重试次数
  120. :return: 回复
  121. """
  122. if retry_count >= 2:
  123. # exit from retry 2 times
  124. logger.warn("[CLAUDEAI] failed after maximum number of retry times")
  125. return Reply(ReplyType.ERROR, "请再问我一次吧")
  126. try:
  127. session_id = context["session_id"]
  128. session = self.sessions.session_query(query, session_id)
  129. model = conf().get("model") or "gpt-3.5-turbo"
  130. # remove system message
  131. if session.messages[0].get("role") == "system":
  132. if model == "wenxin" or model == "claude":
  133. session.messages.pop(0)
  134. logger.info(f"[CLAUDEAI] query={query}")
  135. # do http request
  136. base_url = "https://claude.ai"
  137. payload = json.dumps({
  138. "completion": {
  139. "prompt": f"{query}",
  140. "timezone": "Asia/Kolkata",
  141. "model": "claude-2"
  142. },
  143. "organization_uuid": f"{self.org_uuid}",
  144. "conversation_uuid": f"{self.con_uuid}",
  145. "text": f"{query}",
  146. "attachments": []
  147. })
  148. headers = {
  149. 'User-Agent':
  150. 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
  151. 'Accept': 'text/event-stream, text/event-stream',
  152. 'Accept-Language': 'en-US,en;q=0.5',
  153. 'Referer': 'https://claude.ai/chats',
  154. 'Content-Type': 'application/json',
  155. 'Origin': 'https://claude.ai',
  156. 'DNT': '1',
  157. 'Connection': 'keep-alive',
  158. 'Cookie': f'{self.claude_api_cookie}',
  159. 'Sec-Fetch-Dest': 'empty',
  160. 'Sec-Fetch-Mode': 'cors',
  161. 'Sec-Fetch-Site': 'same-origin',
  162. 'TE': 'trailers'
  163. }
  164. res = requests.post(base_url + "/api/append_message", headers=headers, data=payload,impersonate="chrome110",proxies= self.proxies,timeout=400)
  165. if res.status_code == 200 or "pemission" in res.text:
  166. # execute success
  167. decoded_data = res.content.decode("utf-8")
  168. decoded_data = re.sub('\n+', '\n', decoded_data).strip()
  169. data_strings = decoded_data.split('\n')
  170. completions = []
  171. for data_string in data_strings:
  172. json_str = data_string[6:].strip()
  173. data = json.loads(json_str)
  174. if 'completion' in data:
  175. completions.append(data['completion'])
  176. reply_content = ''.join(completions)
  177. logger.info(f"[CLAUDE] reply={reply_content}, total_tokens=invisible")
  178. self.sessions.session_reply(reply_content, session_id, 100)
  179. return Reply(ReplyType.TEXT, reply_content)
  180. else:
  181. response = res.json()
  182. error = response.get("error")
  183. logger.error(f"[CLAUDE] chat failed, status_code={res.status_code}, "
  184. f"msg={error.get('message')}, type={error.get('type')}, detail: {res.text}, uuid: {self.con_uuid}")
  185. if res.status_code >= 500:
  186. # server error, need retry
  187. time.sleep(2)
  188. logger.warn(f"[CLAUDE] do retry, times={retry_count}")
  189. return self._chat(query, context, retry_count + 1)
  190. return Reply(ReplyType.ERROR, "提问太快啦,请休息一下再问我吧")
  191. except Exception as e:
  192. logger.exception(e)
  193. # retry
  194. time.sleep(2)
  195. logger.warn(f"[CLAUDE] do retry, times={retry_count}")
  196. return self._chat(query, context, retry_count + 1)