Skip to content

Commit

Permalink
Fix API type 3 conversation saving
Browse files Browse the repository at this point in the history
  • Loading branch information
F33RNI committed Mar 14, 2023
1 parent 7458961 commit 9ed8df3
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 30 deletions.
86 changes: 59 additions & 27 deletions AIHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
OTHER DEALINGS IN THE SOFTWARE.
"""
import asyncio
import json
import logging
import os
import queue
Expand Down Expand Up @@ -132,35 +133,54 @@ def set_chat(self, chat_id: int, conversation_id=None, parent_id=None):
chats = {}
save_json(os.path.join(self.chats_dir, 'chats.json'), chats)

def save_conversation(self, chatbot_, conversation_id) -> None:
def save_conversation(self, chatbot_, conversation_id) -> bool:
"""
Saves conversation
:param chatbot_:
:param conversation_id:
:return:
:return: True if no error
"""
logging.info('Saving conversation ' + conversation_id)
# API type 0
if int(self.settings['modules']['chatgpt_api_type']) == 0:
conversations_file = CONVERSATION_DIR_OR_FILE + '.json'
chatbot_.conversations.save(os.path.join(self.chats_dir, conversations_file))

# API type 3
elif int(self.settings['modules']['chatgpt_api_type']) == 3:
if not os.path.exists(os.path.join(self.chats_dir, CONVERSATION_DIR_OR_FILE)):
os.makedirs(os.path.join(self.chats_dir, CONVERSATION_DIR_OR_FILE))
conversation_file = os.path.join(self.chats_dir, CONVERSATION_DIR_OR_FILE, conversation_id + '.json')
chatbot_.save(conversation_file, conversation_id)

def load_conversation(self, chatbot_, conversation_id) -> None:
logging.info('Saving conversation ' + str(conversation_id))
try:
if conversation_id is None:
logging.info('conversation_id is None. Skipping saving')
return False

# API type 0
if int(self.settings['modules']['chatgpt_api_type']) == 0:
conversations_file = CONVERSATION_DIR_OR_FILE + '.json'
chatbot_.conversations.save(os.path.join(self.chats_dir, conversations_file))

# API type 3
elif int(self.settings['modules']['chatgpt_api_type']) == 3:
# Create conversation directory
if not os.path.exists(os.path.join(self.chats_dir, CONVERSATION_DIR_OR_FILE)):
os.makedirs(os.path.join(self.chats_dir, CONVERSATION_DIR_OR_FILE))

# Save as json file
conversation_file = os.path.join(self.chats_dir, CONVERSATION_DIR_OR_FILE,
conversation_id + '.json')
with open(conversation_file, 'w', encoding='utf-8') as json_file:
json.dump(chatbot_.conversation, json_file, indent=4)
json_file.close()
except Exception as e:
logging.error('Error saving conversation ' + str(conversation_id) + ' ' + str(e), e, exc_info=True)
return False
return True

def load_conversation(self, chatbot_, conversation_id) -> bool:
"""
Loads conversation
:param chatbot_:
:param conversation_id:
:return:
:return: True if no error
"""
logging.info('Loading conversation ' + conversation_id)
logging.info('Loading conversation ' + str(conversation_id))
try:
if conversation_id is None:
logging.info('conversation_id is None. Skipping loading')
return False

# API type 0
if int(self.settings['modules']['chatgpt_api_type']) == 0:
conversations_file = CONVERSATION_DIR_OR_FILE + '.json'
Expand All @@ -170,11 +190,16 @@ def load_conversation(self, chatbot_, conversation_id) -> None:
elif int(self.settings['modules']['chatgpt_api_type']) == 3:
conversation_file = os.path.join(self.chats_dir, CONVERSATION_DIR_OR_FILE, conversation_id + '.json')
if os.path.exists(conversation_file):
chatbot_.load(conversation_file, conversation_id)
# Load from json file
with open(conversation_file, 'r', encoding='utf-8') as json_file:
chatbot_.conversation = json.load(json_file)
json_file.close()
else:
logging.warning('File ' + conversation_file + ' not exists!')
except Exception as e:
logging.warning('Error loading conversation ' + conversation_id + ' ' + str(e))
logging.warning('Error loading conversation ' + str(conversation_id) + ' ' + str(e))
return False
return True

def delete_conversation(self, conversation_id) -> None:
"""
Expand Down Expand Up @@ -289,7 +314,8 @@ def gpt_loop(self):

# Try to load conversation
if conversation_id is not None:
self.load_conversation(chatbot, conversation_id)
if not self.load_conversation(chatbot, conversation_id):
conversation_id = None

# Try to load conversation
if conversation_id is not None:
Expand All @@ -312,7 +338,8 @@ def gpt_loop(self):
if conversation_id is None:
conversation_id = str(uuid.uuid4())
chatbot.save_conversation(conversation_id)
self.save_conversation(chatbot, conversation_id)
if not self.save_conversation(chatbot, conversation_id):
conversation_id = None
self.set_chat(container.chat_id, conversation_id, parent_id)
except Exception as e:
logging.warning('Error saving conversation! ' + str(e))
Expand Down Expand Up @@ -375,14 +402,14 @@ async def ask_async(request_, conversation_id_):

# API type 3
elif int(self.settings['modules']['chatgpt_api_type']) == 3:
# Try to load conversation
if not self.load_conversation(chatbot, conversation_id):
conversation_id = None

# Generate conversation ID
if conversation_id is None:
conversation_id = str(uuid.uuid4())

# Try to load conversation
else:
self.load_conversation(chatbot, conversation_id)

# Ask
for data in chatbot.ask(str(container.request), convo_id=conversation_id):
# Initialize response
Expand All @@ -393,9 +420,14 @@ async def ask_async(request_, conversation_id_):
api_response += str(data)

# Save conversation id
self.save_conversation(chatbot, conversation_id)
if not self.save_conversation(chatbot, conversation_id):
conversation_id = None
self.set_chat(container.chat_id, conversation_id)

# Reset conversation
if conversation_id is not None:
chatbot.reset(conversation_id)

# Wrong api type
else:
raise Exception('Wrong chatgpt_api_type')
Expand Down
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import BotHandler
from JSONReaderWriter import load_json

TELEGRAMUS_VERSION = 'beta_2.0.1'
TELEGRAMUS_VERSION = 'beta_2.0.2'

# Logging level (INFO for debug, WARN for release)
LOGGING_LEVEL = logging.INFO
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
psutil>=5.9.1
telegram~=0.0.1
python-telegram-bot~=20.1
revChatGPT==3.3.4
revChatGPT==3.3.5
openai>=0.26.4
tiktoken>=0.2.0
OpenAIAuth>=0.3.2
2 changes: 1 addition & 1 deletion settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"__comment01__": "SPECIFY WHAT MODULES WILL BE INCLUDED IN TELEGRAM BOT AND revChatGPT API TYPE",
"__comment02__": "0 - OFFICIAL CHATGPT API. MORE STUPID MODEL. AUTHORIZATION VIA OPENAI API KEY",
"__comment03__": "1 - SAME AS OFFICIAL WEBSITE. FREE BUT LIMITED NUMBER OF REQUESTS. AUTHORIZATION VIA ACCESS_TOKEN, SESSION_TOKEN (NOT TESTED) OR EMAIL/PASS (NOT TESTED)",
"__comment04__": "2 - (MAY NOT WORK) FREE API FOR CHATGPT. AUTHORIZATION VIA OPENAI API KEY",
"__comment04__": "2 - FREE API FOR CHATGPT. AUTHORIZATION VIA OPENAI API KEY",
"__comment05__": "3 - (RECOMMENDED) OFFICIAL CHATGPT API. AUTHORIZATION VIA OPENAI API KEY",
"modules": {
"chatgpt": true,
Expand Down

0 comments on commit 9ed8df3

Please sign in to comment.