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 9.4KB

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