Browse Source

格式纠正2

master
resphinas 1 year ago
parent
commit
b9e3125610
6 changed files with 9 additions and 34 deletions
  1. +5
    -24
      bot/claude/claude_ai_bot.py
  2. +0
    -4
      common/const.py
  3. +2
    -2
      common/log.py
  4. +2
    -2
      config-template.json
  5. +0
    -1
      lib/itchat/async_components/messages.py
  6. +0
    -1
      lib/itchat/components/messages.py

+ 5
- 24
bot/claude/claude_ai_bot.py View File

@@ -2,7 +2,6 @@ import re
import time import time
import json import json
import uuid import uuid

from curl_cffi import requests from curl_cffi import requests
from bot.bot import Bot from bot.bot import Bot
from bot.chatgpt.chat_gpt_session import ChatGPTSession from bot.chatgpt.chat_gpt_session import ChatGPTSession
@@ -15,10 +14,6 @@ from config import conf




class ClaudeAIBot(Bot, OpenAIImage): class ClaudeAIBot(Bot, OpenAIImage):
# authentication failed
AUTH_FAILED_CODE = 401
NO_QUOTA_CODE = 406

def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "gpt-3.5-turbo") self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "gpt-3.5-turbo")
@@ -32,9 +27,6 @@ class ClaudeAIBot(Bot, OpenAIImage):
self.con_uuid = None self.con_uuid = None
self.get_uuid() self.get_uuid()





def generate_uuid(self): def generate_uuid(self):
random_uuid = uuid.uuid4() random_uuid = uuid.uuid4()
random_uuid_str = str(random_uuid) random_uuid_str = str(random_uuid)
@@ -48,11 +40,8 @@ class ClaudeAIBot(Bot, OpenAIImage):
self.con_uuid = self.generate_uuid() self.con_uuid = self.generate_uuid()
self.create_new_chat() self.create_new_chat()




def get_organization_id(self): def get_organization_id(self):
url = "https://claude.ai/api/organizations" url = "https://claude.ai/api/organizations"

headers = { headers = {
'User-Agent': 'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
@@ -65,12 +54,11 @@ class ClaudeAIBot(Bot, OpenAIImage):
'Connection': 'keep-alive', 'Connection': 'keep-alive',
'Cookie': f'{self.claude_api_cookie}' 'Cookie': f'{self.claude_api_cookie}'
} }

response = requests.get(url, headers=headers,impersonate="chrome110",proxies=self.proxies) response = requests.get(url, headers=headers,impersonate="chrome110",proxies=self.proxies)
res = json.loads(response.text) res = json.loads(response.text)
uuid = res[0]['uuid'] uuid = res[0]['uuid']

return uuid return uuid
def reply(self, query, context: Context = None) -> Reply: def reply(self, query, context: Context = None) -> Reply:
if context.type == ContextType.TEXT: if context.type == ContextType.TEXT:
return self._chat(query, context) return self._chat(query, context)
@@ -108,9 +96,9 @@ class ClaudeAIBot(Bot, OpenAIImage):
print(response.text) print(response.text)


return uuid return uuid
def create_new_chat(self): def create_new_chat(self):
url = f"https://claude.ai/api/organizations/{self.org_uuid}/chat_conversations" url = f"https://claude.ai/api/organizations/{self.org_uuid}/chat_conversations"

payload = json.dumps({"uuid": self.con_uuid, "name": ""}) payload = json.dumps({"uuid": self.con_uuid, "name": ""})
headers = { headers = {
'User-Agent': 'User-Agent':
@@ -127,11 +115,10 @@ class ClaudeAIBot(Bot, OpenAIImage):
'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Site': 'same-origin',
'TE': 'trailers' 'TE': 'trailers'
} }

response = requests.post( url, headers=headers, data=payload,impersonate="chrome110", proxies= self.proxies) response = requests.post( url, headers=headers, data=payload,impersonate="chrome110", proxies= self.proxies)

# Returns JSON of the newly created conversation information # Returns JSON of the newly created conversation information
return response.json() return response.json()
def _chat(self, query, context, retry_count=0) -> Reply: def _chat(self, query, context, retry_count=0) -> Reply:
""" """
发起对话请求 发起对话请求
@@ -146,7 +133,6 @@ class ClaudeAIBot(Bot, OpenAIImage):
return Reply(ReplyType.ERROR, "请再问我一次吧") return Reply(ReplyType.ERROR, "请再问我一次吧")


try: try:

session_id = context["session_id"] session_id = context["session_id"]
session = self.sessions.session_query(query, session_id) session = self.sessions.session_query(query, session_id)
model = conf().get("model") or "gpt-3.5-turbo" model = conf().get("model") or "gpt-3.5-turbo"
@@ -154,8 +140,6 @@ class ClaudeAIBot(Bot, OpenAIImage):
if session.messages[0].get("role") == "system": if session.messages[0].get("role") == "system":
if model == "wenxin": if model == "wenxin":
session.messages.pop(0) session.messages.pop(0)


logger.info(f"[CLAUDEAI] query={query}") logger.info(f"[CLAUDEAI] query={query}")


# do http request # do http request
@@ -189,7 +173,6 @@ class ClaudeAIBot(Bot, OpenAIImage):
} }


res = requests.post(base_url + "/api/append_message", headers=headers, data=payload,impersonate="chrome110",proxies= self.proxies,timeout=400) res = requests.post(base_url + "/api/append_message", headers=headers, data=payload,impersonate="chrome110",proxies= self.proxies,timeout=400)

if res.status_code == 200 or "pemission" in res.text: if res.status_code == 200 or "pemission" in res.text:
# execute success # execute success
decoded_data = res.content.decode("utf-8") decoded_data = res.content.decode("utf-8")
@@ -203,10 +186,9 @@ class ClaudeAIBot(Bot, OpenAIImage):
completions.append(data['completion']) completions.append(data['completion'])


reply_content = ''.join(completions) reply_content = ''.join(completions)
logger.info(f"[CLAUDE] reply={reply_content}, total_tokens=100")
logger.info(f"[CLAUDE] reply={reply_content}, total_tokens=invisible")
self.sessions.session_reply(reply_content, session_id, 100) self.sessions.session_reply(reply_content, session_id, 100)
return Reply(ReplyType.TEXT, reply_content) return Reply(ReplyType.TEXT, reply_content)

else: else:
response = res.json() response = res.json()
error = response.get("error") error = response.get("error")
@@ -218,7 +200,6 @@ class ClaudeAIBot(Bot, OpenAIImage):
time.sleep(2) time.sleep(2)
logger.warn(f"[CLAUDE] do retry, times={retry_count}") logger.warn(f"[CLAUDE] do retry, times={retry_count}")
return self._chat(query, context, retry_count + 1) return self._chat(query, context, retry_count + 1)

return Reply(ReplyType.ERROR, "提问太快啦,请休息一下再问我吧") return Reply(ReplyType.ERROR, "提问太快啦,请休息一下再问我吧")


except Exception as e: except Exception as e:
@@ -226,4 +207,4 @@ class ClaudeAIBot(Bot, OpenAIImage):
# retry # retry
time.sleep(2) time.sleep(2)
logger.warn(f"[CLAUDE] do retry, times={retry_count}") logger.warn(f"[CLAUDE] do retry, times={retry_count}")
return self._chat(query, context, retry_count + 1)
return self._chat(query, context, retry_count + 1)

+ 0
- 4
common/const.py View File

@@ -5,10 +5,6 @@ BAIDU = "baidu"
XUNFEI = "xunfei" XUNFEI = "xunfei"
CHATGPTONAZURE = "chatGPTOnAzure" CHATGPTONAZURE = "chatGPTOnAzure"
LINKAI = "linkai" LINKAI = "linkai"

VERSION = "1.3.0" VERSION = "1.3.0"

MODEL_LIST = ["gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-4", "wenxin", "xunfei"]
CLAUDEAI = "claude" CLAUDEAI = "claude"
VERSION = "1.3.0"
MODEL_LIST = ["gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-4", "wenxin", "xunfei","claude"] MODEL_LIST = ["gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-4", "wenxin", "xunfei","claude"]

+ 2
- 2
common/log.py View File

@@ -13,14 +13,14 @@ def _reset_logger(log):
console_handle.setFormatter( console_handle.setFormatter(
logging.Formatter( logging.Formatter(
"[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s", "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s",
datefmt="%Y-%m-%claude_ai_bot.py%H:%M:%S",
datefmt="%Y-%m-%d %H:%M:%S",
) )
) )
file_handle = logging.FileHandler("run.log", encoding="utf-8") file_handle = logging.FileHandler("run.log", encoding="utf-8")
file_handle.setFormatter( file_handle.setFormatter(
logging.Formatter( logging.Formatter(
"[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s", "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s",
datefmt="%Y-%m-%claude_ai_bot.py%H:%M:%S",
datefmt="%Y-%m-%d %H:%M:%S",
) )
) )
log.addHandler(file_handle) log.addHandler(file_handle)


+ 2
- 2
config-template.json View File

@@ -2,11 +2,11 @@
"open_ai_api_key": "YOUR API KEY", "open_ai_api_key": "YOUR API KEY",
"model": "gpt-3.5-turbo", "model": "gpt-3.5-turbo",
"channel_type": "wx", "channel_type": "wx",
"proxy": "http://127.0.0.1:33210",
"proxy": "",
"hot_reload": false, "hot_reload": false,
"model": "claude", "model": "claude",
"channel_type": "wx", "channel_type": "wx",
"claude_api_cookie": "intercom-device-id-lupk8zyo=b37192f8-c3a5-408d-8525-60ad8c2cc57c; sessionKey=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; intercom-session-lupk8zyo=dHBseWhqVVIvVW4vZU1NMWM3eUpTQldjQkUwYUMwQVlGQ3g4azR6RlQ3ZDBkTTRqQWd4aGN6ZmY4MSt4aEVERy0tdXY0OGdnUTdYdVhsYWx3c2ErUFFTdz09--58fbe081d071984de6a196e49d513761e8b806e9; cf_clearance=9R_XpUT12.KKIRtXlXUFng05L_sdc0GDwz55ZBGsZ6o-1693003153-0-1-636ec5eb.e36b35e5.346f9a0b-0.2.1693003153; __cf_bm=TLFZA8a7JhAo6NRLVIL0jYsD8nb4cDna6slscBAns3A-1693004564-0-AfWzEcpZbRjF6cLEjxhPUnA84TNQDNQofUkZCuabIKkmQan+BlCvvYIeZod8ISJ/RLq1URvIsp++UwTDJyKfLI8=",
"claude_api_cookie": "",
"hot_reload": true, "hot_reload": true,
"single_chat_prefix": [ "single_chat_prefix": [
"bot", "bot",


+ 0
- 1
lib/itchat/async_components/messages.py View File

@@ -350,7 +350,6 @@ def upload_chunk_file(core, fileDir, fileSymbol, fileSize,
('name', (None, fileName)), ('name', (None, fileName)),
('type', (None, fileType)), ('type', (None, fileType)),
('lastModifiedDate', (None, time.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (CST)'))), ('lastModifiedDate', (None, time.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (CST)'))),
('lastModifiedDate', (None, time.strftime('%a %b %claude_ai_bot.py%Y %H:%M:%S GMT+0800 (CST)'))),
('size', (None, str(fileSize))), ('size', (None, str(fileSize))),
('chunks', (None, None)), ('chunks', (None, None)),
('chunk', (None, None)), ('chunk', (None, None)),


+ 0
- 1
lib/itchat/components/messages.py View File

@@ -351,7 +351,6 @@ def upload_chunk_file(core, fileDir, fileSymbol, fileSize,
('name', (None, fileName)), ('name', (None, fileName)),
('type', (None, fileType)), ('type', (None, fileType)),
('lastModifiedDate', (None, time.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (CST)'))), ('lastModifiedDate', (None, time.strftime('%a %b %d %Y %H:%M:%S GMT+0800 (CST)'))),
('lastModifiedDate', (None, time.strftime('%a %b %claude_ai_bot.py%Y %H:%M:%S GMT+0800 (CST)'))),
('size', (None, str(fileSize))), ('size', (None, str(fileSize))),
('chunks', (None, None)), ('chunks', (None, None)),
('chunk', (None, None)), ('chunk', (None, None)),


Loading…
Cancel
Save