Skip to content

Commit 6a1b9c4

Browse files
committed
multi-chat support
1 parent f97489f commit 6a1b9c4

File tree

3 files changed

+29
-14
lines changed

3 files changed

+29
-14
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ A [Telegram bot](https://core.telegram.org/bots/api) that integrates with OpenAI
1818
- [x] (NEW!) Support multiple answers!
1919
- [x] (NEW!) Customizable model parameters (see [configuration](#configuration) section)
2020
- [x] (NEW!) See token usage after each answer
21+
- [x] (NEW!) Multi-chat support
2122

2223
## Coming soon
23-
- [ ] Multi-chat support
2424
- [ ] Image generation using DALL·E APIs
2525

2626
## Additional Features - help needed!

gpt_helper.py

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,25 @@ def __init__(self, config: dict):
1414
"""
1515
openai.api_key = config['api_key']
1616
self.config = config
17-
self.initial_history = [{"role": "system", "content": config['assistant_prompt']}]
18-
self.history = self.initial_history
17+
self.sessions: dict[int: list] = dict() # {chat_id: history}
1918

20-
def get_response(self, query) -> str:
19+
20+
def get_response(self, chat_id: int, query: str) -> str:
2121
"""
2222
Gets a response from the GPT-3 model.
23+
:param chat_id: The chat ID
2324
:param query: The query to send to the model
2425
:return: The answer from the model
2526
"""
2627
try:
27-
self.history.append({"role": "user", "content": query})
28+
if chat_id not in self.sessions:
29+
self.reset_history(chat_id)
30+
31+
self.__add_to_history(chat_id, role="user", content=query)
2832

2933
response = openai.ChatCompletion.create(
3034
model=self.config['model'],
31-
messages=self.history,
35+
messages=self.sessions[chat_id],
3236
temperature=self.config['temperature'],
3337
n=self.config['n_choices'],
3438
max_tokens=self.config['max_tokens'],
@@ -42,13 +46,13 @@ def get_response(self, query) -> str:
4246
if len(response.choices) > 1 and self.config['n_choices'] > 1:
4347
for index, choice in enumerate(response.choices):
4448
if index == 0:
45-
self.history.append({"role": "assistant", "content": choice['message']['content']})
49+
self.__add_to_history(chat_id, role="assistant", content=choice['message']['content'])
4650
answer += f'{index+1}\u20e3\n'
4751
answer += choice['message']['content']
4852
answer += '\n\n'
4953
else:
5054
answer = response.choices[0]['message']['content']
51-
self.history.append({"role": "assistant", "content": answer})
55+
self.__add_to_history(chat_id, role="assistant", content=answer)
5256

5357
if self.config['show_usage']:
5458
answer += "\n\n---\n" \
@@ -63,7 +67,7 @@ def get_response(self, query) -> str:
6367

6468
except openai.error.RateLimitError as e:
6569
logging.exception(e)
66-
return "⚠️ _OpenAI RateLimit exceeded_ ⚠️\nPlease try again in a while."
70+
return f"⚠️ _OpenAI Rate Limit exceeded_ ⚠️\n{str(e)}"
6771

6872
except openai.error.InvalidRequestError as e:
6973
logging.exception(e)
@@ -73,8 +77,19 @@ def get_response(self, query) -> str:
7377
logging.exception(e)
7478
return f"⚠️ _An error has occurred_ ⚠️\n{str(e)}"
7579

76-
def reset_history(self):
80+
81+
def reset_history(self, chat_id):
7782
"""
7883
Resets the conversation history.
7984
"""
80-
self.history = self.initial_history
85+
self.sessions[chat_id] = [{"role": "system", "content": self.config['assistant_prompt']}]
86+
87+
88+
def __add_to_history(self, chat_id, role, content):
89+
"""
90+
Adds a message to the conversation history.
91+
:param chat_id: The chat ID
92+
:param role: The role of the message sender
93+
:param content: The message content
94+
"""
95+
self.sessions[chat_id].append({"role": role, "content": content})

telegram_bot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,12 @@ async def reset(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
3737
Resets the conversation.
3838
"""
3939
if not self.is_allowed(update):
40-
logging.warning(f'User {update.message.from_user.name} is not allowed to reset the bot')
40+
logging.warning(f'User {update.message.from_user.name} is not allowed to reset the conversation')
4141
await self.send_disallowed_message(update, context)
4242
return
4343

4444
logging.info(f'Resetting the conversation for user {update.message.from_user.name}...')
45-
self.gpt.reset_history()
45+
self.gpt.reset_history(chat_id=update.effective_chat.id)
4646
await context.bot.send_message(chat_id=update.effective_chat.id, text='Done!')
4747

4848
async def prompt(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
@@ -57,7 +57,7 @@ async def prompt(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
5757
logging.info(f'New message received from user {update.message.from_user.name}')
5858

5959
await context.bot.send_chat_action(chat_id=update.effective_chat.id, action=constants.ChatAction.TYPING)
60-
response = self.gpt.get_response(update.message.text)
60+
response = self.gpt.get_response(chat_id=update.effective_chat.id, query=update.message.text)
6161
await context.bot.send_message(
6262
chat_id=update.effective_chat.id,
6363
reply_to_message_id=update.message.message_id,

0 commit comments

Comments
 (0)