2023-09-27 23:36:44 -06:00
|
|
|
import json
|
|
|
|
import threading
|
2023-10-27 19:19:22 -06:00
|
|
|
import time
|
2023-09-27 23:36:44 -06:00
|
|
|
import traceback
|
|
|
|
|
|
|
|
import redis as redis_redis
|
|
|
|
|
2024-05-07 12:20:53 -06:00
|
|
|
from llm_server.config.global_config import GlobalConfig
|
2023-09-27 23:36:44 -06:00
|
|
|
from llm_server.llm.openai.moderation import check_moderation_endpoint
|
2023-10-27 19:19:22 -06:00
|
|
|
from llm_server.logging import create_logger
|
2023-09-27 23:36:44 -06:00
|
|
|
|
|
|
|
redis_moderation = redis_redis.Redis()
|
|
|
|
|
|
|
|
|
|
|
|
def start_moderation_workers(num_workers):
|
|
|
|
i = 0
|
|
|
|
for _ in range(num_workers):
|
|
|
|
t = threading.Thread(target=moderation_worker)
|
|
|
|
t.daemon = True
|
|
|
|
t.start()
|
|
|
|
i += 1
|
|
|
|
|
|
|
|
|
2023-10-27 19:19:22 -06:00
|
|
|
# TODO: don't use UUID tags to identify items. Use native redis
|
2023-09-27 23:36:44 -06:00
|
|
|
|
|
|
|
def get_results(tag, num_tasks):
|
2023-10-27 19:19:22 -06:00
|
|
|
tag = str(tag) # Cast a UUID4 to a string.
|
2023-09-27 23:36:44 -06:00
|
|
|
flagged_categories = set()
|
|
|
|
num_results = 0
|
2023-10-27 19:19:22 -06:00
|
|
|
start_time = time.time()
|
2023-09-27 23:36:44 -06:00
|
|
|
while num_results < num_tasks:
|
2024-05-07 12:20:53 -06:00
|
|
|
result = redis_moderation.blpop(['queue:flagged_categories'], timeout=GlobalConfig.get().openai_moderation_timeout)
|
2023-10-27 19:19:22 -06:00
|
|
|
if result is None:
|
|
|
|
break # Timeout occurred, break the loop.
|
2023-09-27 23:36:44 -06:00
|
|
|
result_tag, categories = json.loads(result[1])
|
|
|
|
if result_tag == tag:
|
|
|
|
if categories:
|
|
|
|
for item in categories:
|
|
|
|
flagged_categories.add(item)
|
|
|
|
num_results += 1
|
2024-05-07 12:20:53 -06:00
|
|
|
if time.time() - start_time > GlobalConfig.get().openai_moderation_timeout:
|
2023-10-27 19:19:22 -06:00
|
|
|
logger.warning('Timed out waiting for result from moderator')
|
|
|
|
break
|
2023-09-27 23:36:44 -06:00
|
|
|
return list(flagged_categories)
|
2023-10-27 19:19:22 -06:00
|
|
|
|
|
|
|
|
|
|
|
def moderation_worker():
|
|
|
|
logger = create_logger('moderator')
|
|
|
|
while True:
|
|
|
|
result = redis_moderation.blpop(['queue:msgs_to_check'])
|
|
|
|
try:
|
|
|
|
msg, tag = json.loads(result[1])
|
|
|
|
_, categories = check_moderation_endpoint(msg)
|
|
|
|
redis_moderation.rpush('queue:flagged_categories', json.dumps((tag, categories)))
|
|
|
|
except:
|
|
|
|
logger.error(traceback.format_exc())
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
|
|
def add_moderation_task(msg, tag):
|
|
|
|
redis_moderation.rpush('queue:msgs_to_check', json.dumps((msg, str(tag))))
|