Skip to content

Commit ff11e05

Browse files
authored
Reply message: prompt construction fixed (#27)
1 parent 6d23d26 commit ff11e05

10 files changed

+172
-189
lines changed

changelog.md

+8
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
## [0.2.3] - 2024-04-17
11+
12+
### Changed
13+
14+
- Reply message logic: prompt construction logic is fixed.
15+
- Now, the provider list contains only providers explicitly marked as `working`
16+
17+
1018
## [0.2.2] - 2024-04-16
1119

1220
### Changed

hiroshi/models.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@ def provider(self) -> BaseProvider | RetryProvider:
2626
if not self.provider_name:
2727
return default_model.best_provider
2828
if active_provider := ProviderUtils.convert.get(self.provider_name):
29-
return active_provider
29+
if active_provider.working:
30+
return active_provider
31+
else:
32+
return default_model.best_provider
3033
logger.error(f"Unsupported provider selected: {self.provider_name}. Replacing it with the default one.")
3134
return default_model.best_provider
3235

hiroshi/services/bot.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -55,16 +55,16 @@ async def handle_prompt(db: Database, update: Update, context: ContextTypes.DEFA
5555
if prompt.startswith("/ask"):
5656
prompt = prompt.replace("/ask", "", 1).strip()
5757

58+
# Get replied message concatenated to the prompt.
59+
prompt = get_prompt_with_replied_message(update=update, initial_prompt=prompt)
60+
5861
prompt_to_log = prompt.replace("\r", " ").replace("\n", " ")
5962
logger.info(
6063
f"{telegram_user.name} (Telegram ID: {telegram_user.id}) sent a new message in the "
6164
f"{telegram_chat.type.upper()} chat {telegram_chat.id}"
6265
f"{': ' + prompt_to_log if application_settings.log_prompt_data else ''}"
6366
)
6467

65-
# Get replied message concatenated to the prompt.
66-
prompt = get_prompt_with_replied_message(update=update, prompt=prompt)
67-
6868
get_gtp_chat_answer_task = asyncio.ensure_future(get_gtp_chat_answer(chat_id=telegram_chat.id, prompt=prompt))
6969

7070
while not get_gtp_chat_answer_task.done():

hiroshi/services/gpt.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from loguru import logger
55

66
from hiroshi.config import gpt_settings
7+
from hiroshi.utils import is_provider_active
78

89
MODELS_AND_PROVIDERS: dict[str, tuple[str, str]] = {
910
"Default": ("gpt_35_long", "Default"),
@@ -43,4 +44,8 @@ async def get_chat_response(
4344

4445

4546
def retrieve_available_providers() -> list[str]:
46-
return list(MODELS_AND_PROVIDERS.keys())
47+
return [
48+
key
49+
for key in MODELS_AND_PROVIDERS
50+
if is_provider_active(MODELS_AND_PROVIDERS[key]) or "Default" in MODELS_AND_PROVIDERS[key]
51+
]

hiroshi/utils.py

+29-13
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from typing import Any, Callable
44

55
import httpx
6+
from g4f.Provider import ProviderUtils
67
from loguru import logger
78
from telegram import Chat as TelegramChat
89
from telegram import Message as TelegramMessage
@@ -36,14 +37,19 @@ def get_telegram_message(update: Update) -> TelegramMessage:
3637
raise ValueError(f"Telegram incoming update does not contain valid message data. Update ID: {update.update_id}")
3738

3839

39-
def get_prompt_with_replied_message(update: Update, prompt: str) -> str:
40+
def get_prompt_with_replied_message(update: Update, initial_prompt: str) -> str:
41+
if not update.message or not update.message.reply_to_message:
42+
return initial_prompt
43+
4044
user = get_telegram_user(update)
45+
if quoted_user := update.message.reply_to_message.from_user:
46+
quoted_user_name = quoted_user.name
47+
else:
48+
quoted_user_name = "user"
49+
50+
quoted_message = update.message.reply_to_message.caption or update.message.reply_to_message.text
51+
prompt = f"> {quoted_message}\n>\n> — *{quoted_user_name}*\n\n" f"{user.username}: {initial_prompt}"
4152

42-
if update.message and update.message.reply_to_message:
43-
prompt = (f'<<{update.message.reply_to_message.caption or update.message.reply_to_message.text}.>> '
44-
f'{user.username} answered: {prompt}')
45-
if update.message.reply_to_message.from_user:
46-
prompt = f' {update.message.reply_to_message.from_user.username} said: ' + prompt
4753
return prompt
4854

4955

@@ -243,9 +249,11 @@ def log_application_settings() -> None:
243249
logger_info = "<red>DISABLED</red>."
244250

245251
if application_settings.monitoring_url:
246-
logger_info = (f"<blue>ACTIVE</blue>."
247-
f"MONITORING_FREQUENCY_CALL=<blue>{application_settings.monitoring_frequency_call}</blue>."
248-
f"MONITORING_URL=<blue>{application_settings.monitoring_url}</blue>")
252+
logger_info = (
253+
f"<blue>ACTIVE</blue>."
254+
f"MONITORING_FREQUENCY_CALL=<blue>{application_settings.monitoring_frequency_call}</blue>."
255+
f"MONITORING_URL=<blue>{application_settings.monitoring_url}</blue>"
256+
)
249257

250258
messages = (
251259
f"Application is initialized using {storage} storage.",
@@ -273,14 +281,22 @@ async def run_monitoring(context: ContextTypes.DEFAULT_TYPE) -> None:
273281
if not application_settings.monitoring_url:
274282
return
275283

276-
transport = httpx.AsyncHTTPTransport(retries=application_settings.monitoring_retry_calls,
277-
proxy=application_settings.monitoring_proxy)
284+
transport = httpx.AsyncHTTPTransport(
285+
retries=application_settings.monitoring_retry_calls, proxy=application_settings.monitoring_proxy
286+
)
278287

279288
async with httpx.AsyncClient(transport=transport, proxy=application_settings.monitoring_proxy) as client:
280289
try:
281290
result = await client.get(application_settings.monitoring_url)
282291
except Exception as error:
283-
logger.error(f'Uptime Checker failed with an Exception: {error}')
292+
logger.error(f"Uptime Checker failed with an Exception: {error}")
284293
return
285294
if result.is_error:
286-
logger.error(f'Uptime Checker failed. status_code({result.status_code}) msg: {result.text}')
295+
logger.error(f"Uptime Checker failed. status_code({result.status_code}) msg: {result.text}")
296+
297+
298+
def is_provider_active(model_and_provider_names: tuple[str, str]) -> bool:
299+
_, provider_name = model_and_provider_names
300+
if provider := ProviderUtils.convert.get(provider_name):
301+
return bool(provider.working)
302+
return False

main.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
filters,
1818
)
1919

20-
from hiroshi.config import telegram_settings, application_settings
20+
from hiroshi.config import application_settings, telegram_settings
2121
from hiroshi.services.bot import (
2222
handle_available_providers_options,
2323
handle_prompt,
@@ -165,11 +165,11 @@ def run(self) -> None:
165165
# )
166166
app.add_error_handler(self.error_handler)
167167
if not app.job_queue:
168-
logger.error('Application job queue was shut down or never started.')
168+
logger.error("Application job queue was shut down or never started.")
169169
else:
170-
app.job_queue.run_repeating(callback=run_monitoring,
171-
interval=application_settings.monitoring_frequency_call,
172-
first=0.0)
170+
app.job_queue.run_repeating(
171+
callback=run_monitoring, interval=application_settings.monitoring_frequency_call, first=0.0
172+
)
173173

174174
app.run_polling()
175175

0 commit comments

Comments
 (0)