-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage_buffer.py
More file actions
58 lines (40 loc) · 1.78 KB
/
message_buffer.py
File metadata and controls
58 lines (40 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import asyncio
import redis.asyncio as redis
from collections import defaultdict
from config import REDIS_URL, BUFFER_KEY_SUFIX, DEBOUNCE_SECONDS, BUFFER_TTL
from evolution_api import send_whatsapp_message
from chains import get_conversational_rag_chain
redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)
conversational_rag_chain = get_conversational_rag_chain()
debounce_tasks = defaultdict(asyncio.Task)
def log(*args):
print('[BUFFER]', *args)
async def buffer_message(chat_id: str, message: str):
buffer_key = f'{chat_id}{BUFFER_KEY_SUFIX}'
await redis_client.rpush(buffer_key, message)
await redis_client.expire(buffer_key, BUFFER_TTL)\
log(f'Mensagem adicionada ao buffer de {chat_id}: {message}')
if debounce_tasks.get(chat_id):
debounce_tasks[chat_id].cancel()
log(f'Debounce resetado para {chat_id}')
debounce_tasks[chat_id] = asyncio.create_task(handle_debounce(chat_id))
async def handle_debounce(chat_id: str):
try:
log(f'Iniciando debounce para {chat_id}')
await asyncio.sleep(float(DEBOUNCE_SECONDS))
buffer_key = f'{chat_id}{BUFFER_KEY_SUFIX}'
messages = await redis_client.lrange(buffer_key, 0, -1)
full_message = ' '.join(messages).strip()
if full_message:
log(f'Enviando mensagem agrupada para {chat_id}: {full_message}')
ai_response = conversational_rag_chain.invoke(
input={'input': full_message},
config={'configurable': {'session_id': chat_id}},
)['answer']
send_whatsapp_message(
number=chat_id,
text=ai_response,
)
await redis_client.delete(buffer_key)
except asyncio.CancelledError:
log(f'Debounce cancelado para {chat_id}')