format code

This commit is contained in:
hibobmaster 2023-04-11 13:42:43 +08:00
parent f5ccc67258
commit da682cb9fd
Signed by: bobmaster
GPG key ID: 316B77D7914D713C
5 changed files with 56 additions and 48 deletions

View file

@ -49,7 +49,6 @@ wait_message = "Waiting for results..."
download_message = "\nDownloading images..."
def debug(debug_file, text_var):
"""helper function for debug"""
with open(f"{debug_file}", "a") as f:
@ -74,7 +73,6 @@ class ImageGen:
if self.debug_file:
self.debug = partial(debug, self.debug_file)
def get_images(self, prompt: str) -> list:
"""
Fetches image links from Bing
@ -106,7 +104,8 @@ class ImageGen:
if response.status_code != 302:
# if rt4 fails, try rt3
url = f"{BING_URL}/images/create?q={url_encoded_prompt}&rt=3&FORM=GENCRE"
response3 = self.session.post(url, allow_redirects=False, timeout=200)
response3 = self.session.post(
url, allow_redirects=False, timeout=200)
if response3.status_code != 302:
if self.debug_file:
self.debug(f"ERROR: {error_redirect}")

6
log.py
View file

@ -14,8 +14,10 @@ def getlogger():
info_handler.setLevel(logging.INFO)
# create formatters
warn_format = logging.Formatter('%(name)s - %(funcName)s - %(levelname)s - %(message)s')
error_format = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
warn_format = logging.Formatter(
'%(name)s - %(funcName)s - %(levelname)s - %(message)s')
error_format = logging.Formatter(
'%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
info_format = logging.Formatter('%(message)s')
# set formatter

13
main.py
View file

@ -6,6 +6,7 @@ from log import getlogger
logger = getlogger()
async def main():
if os.path.exists('config.json'):
@ -13,7 +14,7 @@ async def main():
config = json.load(fp)
matrix_bot = Bot(homeserver=config.get('homeserver'),
user_id=config.get('user_id') ,
user_id=config.get('user_id'),
password=config.get('password'),
device_id=config.get('device_id'),
room_id=config.get('room_id'),
@ -27,16 +28,18 @@ async def main():
else:
matrix_bot = Bot(homeserver=os.environ.get('HOMESERVER'),
user_id=os.environ.get('USER_ID') ,
user_id=os.environ.get('USER_ID'),
password=os.environ.get('PASSWORD'),
device_id=os.environ.get("DEVICE_ID"),
room_id=os.environ.get("ROOM_ID"),
api_key=os.environ.get("OPENAI_API_KEY"),
bing_api_endpoint=os.environ.get("BING_API_ENDPOINT"),
access_token=os.environ.get("ACCESS_TOKEN"),
jailbreakEnabled=os.environ.get("JAILBREAKENABLED", "false").lower() in ('true', '1', 't'),
jailbreakEnabled=os.environ.get(
"JAILBREAKENABLED", "false").lower() in ('true', '1', 't'),
bing_auth_cookie=os.environ.get("BING_AUTH_COOKIE"),
markdown_formatted=os.environ.get("MARKDOWN_FORMATTED", "false").lower() in ('true', '1', 't'),
markdown_formatted=os.environ.get(
"MARKDOWN_FORMATTED", "false").lower() in ('true', '1', 't'),
)
await matrix_bot.login()
@ -50,5 +53,3 @@ async def main():
if __name__ == "__main__":
logger.info("matrix chatgpt bot start.....")
asyncio.run(main())

View file

@ -36,7 +36,8 @@ async def send_room_image(client: AsyncClient,
await client.room_send(
room_id,
message_type="m.room.message",
content={"msgtype": "m.text", "body": f"Failed to generate image. Failure response: {resp}", },
content={"msgtype": "m.text",
"body": f"Failed to generate image. Failure response: {resp}", },
ignore_unverified_devices=True,
)
return
@ -56,4 +57,5 @@ async def send_room_image(client: AsyncClient,
try:
await client.room_send(room_id, message_type="m.room.message", content=content)
except Exception as e:
logger.error(f"Image send of file {image} failed.\n Error: {e}", exc_info=True)
logger.error(
f"Image send of file {image} failed.\n Error: {e}", exc_info=True)

24
v3.py
View file

@ -53,7 +53,8 @@ class Chatbot:
},
)
proxy = (
proxy or os.environ.get("all_proxy") or os.environ.get("ALL_PROXY") or None
proxy or os.environ.get(
"all_proxy") or os.environ.get("ALL_PROXY") or None
)
if proxy:
@ -79,7 +80,6 @@ class Chatbot:
],
}
def add_to_conversation(
self,
message: str,
@ -105,7 +105,6 @@ class Chatbot:
else:
break
def get_token_count(self, convo_id: str = "default") -> int:
"""
Get token count
@ -158,8 +157,10 @@ class Chatbot:
self.__truncate_conversation(convo_id=convo_id)
# Get response
response = self.session.post(
os.environ.get("API_URL") or "https://api.openai.com/v1/chat/completions",
headers={"Authorization": f"Bearer {kwargs.get('api_key', self.api_key)}"},
os.environ.get(
"API_URL") or "https://api.openai.com/v1/chat/completions",
headers={
"Authorization": f"Bearer {kwargs.get('api_key', self.api_key)}"},
json={
"model": self.engine,
"messages": self.conversation[convo_id],
@ -205,7 +206,8 @@ class Chatbot:
content = delta["content"]
full_response += content
yield content
self.add_to_conversation(full_response, response_role, convo_id=convo_id)
self.add_to_conversation(
full_response, response_role, convo_id=convo_id)
async def ask_stream_async(
self,
@ -225,8 +227,10 @@ class Chatbot:
# Get response
async with self.aclient.stream(
"post",
os.environ.get("API_URL") or "https://api.openai.com/v1/chat/completions",
headers={"Authorization": f"Bearer {kwargs.get('api_key', self.api_key)}"},
os.environ.get(
"API_URL") or "https://api.openai.com/v1/chat/completions",
headers={
"Authorization": f"Bearer {kwargs.get('api_key', self.api_key)}"},
json={
"model": self.engine,
"messages": self.conversation[convo_id],
@ -274,7 +278,8 @@ class Chatbot:
content: str = delta["content"]
full_response += content
yield content
self.add_to_conversation(full_response, response_role, convo_id=convo_id)
self.add_to_conversation(
full_response, response_role, convo_id=convo_id)
async def ask_async(
self,
@ -314,7 +319,6 @@ class Chatbot:
full_response: str = "".join(response)
return full_response
def reset(self, convo_id: str = "default", system_prompt: str = None) -> None:
"""
Reset the conversation