Skip to content

Commit

Permalink
Revert "Init procrastinate worker + moved openai queries to async tasks"
Browse files Browse the repository at this point in the history
This reverts commit 165a0cc.
  • Loading branch information
Kudryashov Lev committed Jul 31, 2023
1 parent aa9c547 commit a0e72fc
Show file tree
Hide file tree
Showing 8 changed files with 141 additions and 193 deletions.
38 changes: 0 additions & 38 deletions bread_bot/common/async_tasks.py

This file was deleted.

17 changes: 12 additions & 5 deletions bread_bot/common/routes/common.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
from typing import List

from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from sqlalchemy.ext.asyncio import AsyncSession
from starlette import status

Expand All @@ -24,11 +24,18 @@
RESPONSE_OK = "OK"


async def _handle_message(db, request_body):
message_receiver = MessageReceiver(db=db, request_body=request_body)
message = await message_receiver.receive()
message_sender = MessageSender(message=message)
await message_sender.send_messages_to_chat()


@router.post("/")
async def handle_message(request_body: StandardBodySchema, db: AsyncSession = Depends(get_async_session)):
await MessageSender(
message=await MessageReceiver(db=db, request_body=request_body).receive()
).send_messages_to_chat()
async def handle_message(
request_body: StandardBodySchema, background_tasks: BackgroundTasks, db: AsyncSession = Depends(get_async_session)
):
background_tasks.add_task(_handle_message, db, request_body)
return RESPONSE_OK


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from sqlalchemy import select, and_

from bread_bot.common.async_tasks import async_free_promt, async_think_about
from bread_bot.common.clients.openai_client import get_chat_gpt_client # noqa
from bread_bot.common.exceptions.base import NextStepException, RaiseUpException
from bread_bot.common.models import AnswerEntity
Expand Down Expand Up @@ -188,21 +187,14 @@ async def morph_word(self, debug: bool = False):
async def think_about(self):
if not self.member_service.chat.is_openai_enabled:
raise RaiseUpException("Для данной группы функция недоступна.")
async_think_about.defer(
pre_promt=self.command_instance.raw_command,
text=self.command_instance.rest_text,
chat_id=self.member_service.chat.chat_id,
reply_to_message_id=self.message_service.message.message_id,
)
things = await OpenAIService().think_about(self.command_instance.raw_command, self.command_instance.rest_text)
return self._return_answer(things)

async def free_openai_query(self):
if not self.member_service.chat.is_openai_enabled:
raise RaiseUpException("Для данной группы функция недоступна.")
async_free_promt.defer(
text=self.command_instance.rest_text,
chat_id=self.member_service.chat.chat_id,
reply_to_message_id=self.message_service.message.message_id,
)
result = await OpenAIService().free_promt(self.command_instance.rest_text)
return self._return_answer(result)

def help(self):
if not self.command_instance.rest_text:
Expand Down
10 changes: 0 additions & 10 deletions bread_bot/main/procrastinate.py

This file was deleted.

67 changes: 17 additions & 50 deletions bread_bot/tests/test_common/test_think_feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

import pytest
from fastapi.testclient import TestClient
from pytest_mock import MockerFixture

from bread_bot.common.async_tasks import async_free_promt, async_think_about
from bread_bot.common.schemas.telegram_messages import (
StandardBodySchema,
MessageSchema,
Expand Down Expand Up @@ -35,20 +35,6 @@ def wrap(message_text: str = "") -> StandardBodySchema:
return wrap


@pytest.fixture
def think_about_defer(mocker):
return mocker.patch(
"bread_bot.common.services.handlers.command_methods.entertainment_command_method.async_think_about.defer"
)


@pytest.fixture
def free_promt_defer(mocker):
return mocker.patch(
"bread_bot.common.services.handlers.command_methods.entertainment_command_method.async_free_promt.defer"
)


async def test_can_handle_message(message_factory):
body = message_factory().dict()
response = client.post(
Expand All @@ -66,70 +52,51 @@ async def test_what_you_think_is_available(db, message_factory):

message_receiver = MessageReceiver(db=db, request_body=body)
message = await message_receiver.receive()

assert message is not None


async def test_chat_gpt_excepted(db, chat_factory, message_factory, think_about_defer):
async def test_chat_gpt_excepted(db, chat_factory, message_factory):
message = f"{BOT_NAME} что думаешь про воду"
body = message_factory(message)
await chat_factory(chat_id=body.message.source.id, name="lol", is_openai_enabled=True)
message_receiver = MessageReceiver(db=db, request_body=body)

await message_receiver.receive()
think_about_defer.assert_called_once()
result = await message_receiver.receive()

assert result.text == "Ошибка работы получения ответа"


async def test_what_you_think(db, chat_factory, message_factory, think_about_defer):
async def test_what_you_think(db, chat_factory, message_factory, mocker: MockerFixture):
message = f"{BOT_NAME} что думаешь про воду"
body = message_factory(message)
await chat_factory(chat_id=body.message.source.id, name="lol", is_openai_enabled=True)
message_receiver = MessageReceiver(db=db, request_body=body)
await message_receiver.receive()
think_about_defer.assert_called_once_with(
pre_promt="что думаешь про", text="воду", chat_id=body.message.source.id, reply_to_message_id=1
)


async def test_what_you_think_task(mocker):
spy = AsyncMock(return_value="Нормальный ответ на промт")
spy = AsyncMock(return_value="Вода чертовски хороша!")
mocker.patch(
"bread_bot.common.services.think_service.get_chat_gpt_client",
return_value=MagicMock(get_chatgpt_answer=spy),
)
send_mock = mocker.patch("bread_bot.common.clients.telegram_client.TelegramClient.send")
await async_think_about(pre_promt="что думаешь про", text="LOL", chat_id=1, reply_to_message_id=1)
send_mock.assert_called_once_with(
**{
"data": {"chat_id": 1, "reply_to_message_id": 1, "text": "Нормальный ответ на промт"},
"method": "sendMessage",
}
result = await message_receiver.receive()
assert result.text == "Вода чертовски хороша!"
spy.assert_called_once_with(
f"что думаешь про воду. Уложись в три-четыре предложения. Расскажи об этом в "
f"юмористической и саркастической форме."
)


async def test_free_promt(db, chat_factory, message_factory, free_promt_defer):
async def test_free_promt(db, chat_factory, message_factory, mocker: MockerFixture):
message = f"{BOT_NAME} promt какой-то несложный промт"
body = message_factory(message)
await chat_factory(chat_id=body.message.source.id, name="lol", is_openai_enabled=True)
message_receiver = MessageReceiver(db=db, request_body=body)
await message_receiver.receive()
free_promt_defer.assert_called_once_with(
text="какой-то несложный промт",
chat_id=body.message.source.id,
reply_to_message_id=1,
)


async def test_free_promt_task(mocker):
spy = AsyncMock(return_value="Нормальный ответ на промт")
mocker.patch(
"bread_bot.common.services.think_service.get_chat_gpt_client",
return_value=MagicMock(get_chatgpt_answer=spy),
)
send_mock = mocker.patch("bread_bot.common.clients.telegram_client.TelegramClient.send")
await async_free_promt(text="LOL", chat_id=1, reply_to_message_id=1)
send_mock.assert_called_once_with(
**{
"data": {"chat_id": 1, "reply_to_message_id": 1, "text": "Нормальный ответ на промт"},
"method": "sendMessage",
}
)
result = await message_receiver.receive()
assert result.text == "Нормальный ответ на промт"
spy.assert_called_once_with("какой-то несложный промт")
13 changes: 1 addition & 12 deletions ci/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,6 @@ services:
- bread_bot_net
depends_on:
- postgres
bread_bot_worker:
image: levkey/bread_bot:app
restart: unless-stopped
command: bash -c "procrastinate --app=bread_bot.main.procrastinate.app schema --apply && procrastinate --verbose --app=bread_bot.main.procrastinate.app worker"
env_file:
- /root/environments.env
networks:
- bread_bot_net
depends_on:
- postgres
- bread_bot
postgres:
image: postgres:13.3
volumes:
Expand All @@ -52,4 +41,4 @@ networks:
bread_bot_net:
external: True
volumes:
pgdata:
pgdata:
Loading

0 comments on commit a0e72fc

Please sign in to comment.