format code
This commit is contained in:
parent
f5ccc67258
commit
da682cb9fd
5 changed files with 56 additions and 48 deletions
|
@ -49,7 +49,6 @@ wait_message = "Waiting for results..."
|
||||||
download_message = "\nDownloading images..."
|
download_message = "\nDownloading images..."
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def debug(debug_file, text_var):
|
def debug(debug_file, text_var):
|
||||||
"""helper function for debug"""
|
"""helper function for debug"""
|
||||||
with open(f"{debug_file}", "a") as f:
|
with open(f"{debug_file}", "a") as f:
|
||||||
|
@ -74,7 +73,6 @@ class ImageGen:
|
||||||
if self.debug_file:
|
if self.debug_file:
|
||||||
self.debug = partial(debug, self.debug_file)
|
self.debug = partial(debug, self.debug_file)
|
||||||
|
|
||||||
|
|
||||||
def get_images(self, prompt: str) -> list:
|
def get_images(self, prompt: str) -> list:
|
||||||
"""
|
"""
|
||||||
Fetches image links from Bing
|
Fetches image links from Bing
|
||||||
|
@ -106,7 +104,8 @@ class ImageGen:
|
||||||
if response.status_code != 302:
|
if response.status_code != 302:
|
||||||
# if rt4 fails, try rt3
|
# if rt4 fails, try rt3
|
||||||
url = f"{BING_URL}/images/create?q={url_encoded_prompt}&rt=3&FORM=GENCRE"
|
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 response3.status_code != 302:
|
||||||
if self.debug_file:
|
if self.debug_file:
|
||||||
self.debug(f"ERROR: {error_redirect}")
|
self.debug(f"ERROR: {error_redirect}")
|
||||||
|
|
6
log.py
6
log.py
|
@ -14,8 +14,10 @@ def getlogger():
|
||||||
info_handler.setLevel(logging.INFO)
|
info_handler.setLevel(logging.INFO)
|
||||||
|
|
||||||
# create formatters
|
# create formatters
|
||||||
warn_format = logging.Formatter('%(name)s - %(funcName)s - %(levelname)s - %(message)s')
|
warn_format = logging.Formatter(
|
||||||
error_format = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
|
'%(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')
|
info_format = logging.Formatter('%(message)s')
|
||||||
|
|
||||||
# set formatter
|
# set formatter
|
||||||
|
|
13
main.py
13
main.py
|
@ -6,6 +6,7 @@ from log import getlogger
|
||||||
|
|
||||||
logger = getlogger()
|
logger = getlogger()
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
|
|
||||||
if os.path.exists('config.json'):
|
if os.path.exists('config.json'):
|
||||||
|
@ -13,7 +14,7 @@ async def main():
|
||||||
config = json.load(fp)
|
config = json.load(fp)
|
||||||
|
|
||||||
matrix_bot = Bot(homeserver=config.get('homeserver'),
|
matrix_bot = Bot(homeserver=config.get('homeserver'),
|
||||||
user_id=config.get('user_id') ,
|
user_id=config.get('user_id'),
|
||||||
password=config.get('password'),
|
password=config.get('password'),
|
||||||
device_id=config.get('device_id'),
|
device_id=config.get('device_id'),
|
||||||
room_id=config.get('room_id'),
|
room_id=config.get('room_id'),
|
||||||
|
@ -27,16 +28,18 @@ async def main():
|
||||||
|
|
||||||
else:
|
else:
|
||||||
matrix_bot = Bot(homeserver=os.environ.get('HOMESERVER'),
|
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'),
|
password=os.environ.get('PASSWORD'),
|
||||||
device_id=os.environ.get("DEVICE_ID"),
|
device_id=os.environ.get("DEVICE_ID"),
|
||||||
room_id=os.environ.get("ROOM_ID"),
|
room_id=os.environ.get("ROOM_ID"),
|
||||||
api_key=os.environ.get("OPENAI_API_KEY"),
|
api_key=os.environ.get("OPENAI_API_KEY"),
|
||||||
bing_api_endpoint=os.environ.get("BING_API_ENDPOINT"),
|
bing_api_endpoint=os.environ.get("BING_API_ENDPOINT"),
|
||||||
access_token=os.environ.get("ACCESS_TOKEN"),
|
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"),
|
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()
|
await matrix_bot.login()
|
||||||
|
@ -50,5 +53,3 @@ async def main():
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
logger.info("matrix chatgpt bot start.....")
|
logger.info("matrix chatgpt bot start.....")
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -36,7 +36,8 @@ async def send_room_image(client: AsyncClient,
|
||||||
await client.room_send(
|
await client.room_send(
|
||||||
room_id,
|
room_id,
|
||||||
message_type="m.room.message",
|
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,
|
ignore_unverified_devices=True,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
@ -56,4 +57,5 @@ async def send_room_image(client: AsyncClient,
|
||||||
try:
|
try:
|
||||||
await client.room_send(room_id, message_type="m.room.message", content=content)
|
await client.room_send(room_id, message_type="m.room.message", content=content)
|
||||||
except Exception as e:
|
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
24
v3.py
|
@ -53,7 +53,8 @@ class Chatbot:
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
proxy = (
|
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:
|
if proxy:
|
||||||
|
@ -79,7 +80,6 @@ class Chatbot:
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def add_to_conversation(
|
def add_to_conversation(
|
||||||
self,
|
self,
|
||||||
message: str,
|
message: str,
|
||||||
|
@ -105,7 +105,6 @@ class Chatbot:
|
||||||
else:
|
else:
|
||||||
break
|
break
|
||||||
|
|
||||||
|
|
||||||
def get_token_count(self, convo_id: str = "default") -> int:
|
def get_token_count(self, convo_id: str = "default") -> int:
|
||||||
"""
|
"""
|
||||||
Get token count
|
Get token count
|
||||||
|
@ -158,8 +157,10 @@ class Chatbot:
|
||||||
self.__truncate_conversation(convo_id=convo_id)
|
self.__truncate_conversation(convo_id=convo_id)
|
||||||
# Get response
|
# Get response
|
||||||
response = self.session.post(
|
response = self.session.post(
|
||||||
os.environ.get("API_URL") or "https://api.openai.com/v1/chat/completions",
|
os.environ.get(
|
||||||
headers={"Authorization": f"Bearer {kwargs.get('api_key', self.api_key)}"},
|
"API_URL") or "https://api.openai.com/v1/chat/completions",
|
||||||
|
headers={
|
||||||
|
"Authorization": f"Bearer {kwargs.get('api_key', self.api_key)}"},
|
||||||
json={
|
json={
|
||||||
"model": self.engine,
|
"model": self.engine,
|
||||||
"messages": self.conversation[convo_id],
|
"messages": self.conversation[convo_id],
|
||||||
|
@ -205,7 +206,8 @@ class Chatbot:
|
||||||
content = delta["content"]
|
content = delta["content"]
|
||||||
full_response += content
|
full_response += content
|
||||||
yield 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(
|
async def ask_stream_async(
|
||||||
self,
|
self,
|
||||||
|
@ -225,8 +227,10 @@ class Chatbot:
|
||||||
# Get response
|
# Get response
|
||||||
async with self.aclient.stream(
|
async with self.aclient.stream(
|
||||||
"post",
|
"post",
|
||||||
os.environ.get("API_URL") or "https://api.openai.com/v1/chat/completions",
|
os.environ.get(
|
||||||
headers={"Authorization": f"Bearer {kwargs.get('api_key', self.api_key)}"},
|
"API_URL") or "https://api.openai.com/v1/chat/completions",
|
||||||
|
headers={
|
||||||
|
"Authorization": f"Bearer {kwargs.get('api_key', self.api_key)}"},
|
||||||
json={
|
json={
|
||||||
"model": self.engine,
|
"model": self.engine,
|
||||||
"messages": self.conversation[convo_id],
|
"messages": self.conversation[convo_id],
|
||||||
|
@ -274,7 +278,8 @@ class Chatbot:
|
||||||
content: str = delta["content"]
|
content: str = delta["content"]
|
||||||
full_response += content
|
full_response += content
|
||||||
yield 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(
|
async def ask_async(
|
||||||
self,
|
self,
|
||||||
|
@ -314,7 +319,6 @@ class Chatbot:
|
||||||
full_response: str = "".join(response)
|
full_response: str = "".join(response)
|
||||||
return full_response
|
return full_response
|
||||||
|
|
||||||
|
|
||||||
def reset(self, convo_id: str = "default", system_prompt: str = None) -> None:
|
def reset(self, convo_id: str = "default", system_prompt: str = None) -> None:
|
||||||
"""
|
"""
|
||||||
Reset the conversation
|
Reset the conversation
|
||||||
|
|
Loading…
Reference in a new issue