您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

223 行
8.9KB

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