output_moderation.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import logging
  2. import threading
  3. import time
  4. from typing import Any, Optional
  5. from flask import Flask, current_app
  6. from pydantic import BaseModel, ConfigDict
  7. from core.app.apps.base_app_queue_manager import AppQueueManager, PublishFrom
  8. from core.app.entities.queue_entities import QueueMessageReplaceEvent
  9. from core.moderation.base import ModerationAction, ModerationOutputsResult
  10. from core.moderation.factory import ModerationFactory
  11. logger = logging.getLogger(__name__)
  12. class ModerationRule(BaseModel):
  13. type: str
  14. config: dict[str, Any]
  15. class OutputModeration(BaseModel):
  16. DEFAULT_BUFFER_SIZE: int = 300
  17. tenant_id: str
  18. app_id: str
  19. rule: ModerationRule
  20. queue_manager: AppQueueManager
  21. thread: Optional[threading.Thread] = None
  22. thread_running: bool = True
  23. buffer: str = ''
  24. is_final_chunk: bool = False
  25. final_output: Optional[str] = None
  26. model_config = ConfigDict(arbitrary_types_allowed=True)
  27. def should_direct_output(self):
  28. return self.final_output is not None
  29. def get_final_output(self):
  30. return self.final_output
  31. def append_new_token(self, token: str):
  32. self.buffer += token
  33. if not self.thread:
  34. self.thread = self.start_thread()
  35. def moderation_completion(self, completion: str, public_event: bool = False) -> str:
  36. self.buffer = completion
  37. self.is_final_chunk = True
  38. result = self.moderation(
  39. tenant_id=self.tenant_id,
  40. app_id=self.app_id,
  41. moderation_buffer=completion
  42. )
  43. if not result or not result.flagged:
  44. return completion
  45. if result.action == ModerationAction.DIRECT_OUTPUT:
  46. final_output = result.preset_response
  47. else:
  48. final_output = result.text
  49. if public_event:
  50. self.queue_manager.publish(
  51. QueueMessageReplaceEvent(
  52. text=final_output
  53. ),
  54. PublishFrom.TASK_PIPELINE
  55. )
  56. return final_output
  57. def start_thread(self) -> threading.Thread:
  58. buffer_size = int(current_app.config.get('MODERATION_BUFFER_SIZE', self.DEFAULT_BUFFER_SIZE))
  59. thread = threading.Thread(target=self.worker, kwargs={
  60. 'flask_app': current_app._get_current_object(),
  61. 'buffer_size': buffer_size if buffer_size > 0 else self.DEFAULT_BUFFER_SIZE
  62. })
  63. thread.start()
  64. return thread
  65. def stop_thread(self):
  66. if self.thread and self.thread.is_alive():
  67. self.thread_running = False
  68. def worker(self, flask_app: Flask, buffer_size: int):
  69. with flask_app.app_context():
  70. current_length = 0
  71. while self.thread_running:
  72. moderation_buffer = self.buffer
  73. buffer_length = len(moderation_buffer)
  74. if not self.is_final_chunk:
  75. chunk_length = buffer_length - current_length
  76. if 0 <= chunk_length < buffer_size:
  77. time.sleep(1)
  78. continue
  79. current_length = buffer_length
  80. result = self.moderation(
  81. tenant_id=self.tenant_id,
  82. app_id=self.app_id,
  83. moderation_buffer=moderation_buffer
  84. )
  85. if not result or not result.flagged:
  86. continue
  87. if result.action == ModerationAction.DIRECT_OUTPUT:
  88. final_output = result.preset_response
  89. self.final_output = final_output
  90. else:
  91. final_output = result.text + self.buffer[len(moderation_buffer):]
  92. # trigger replace event
  93. if self.thread_running:
  94. self.queue_manager.publish(
  95. QueueMessageReplaceEvent(
  96. text=final_output
  97. ),
  98. PublishFrom.TASK_PIPELINE
  99. )
  100. if result.action == ModerationAction.DIRECT_OUTPUT:
  101. break
  102. def moderation(self, tenant_id: str, app_id: str, moderation_buffer: str) -> Optional[ModerationOutputsResult]:
  103. try:
  104. moderation_factory = ModerationFactory(
  105. name=self.rule.type,
  106. app_id=app_id,
  107. tenant_id=tenant_id,
  108. config=self.rule.config
  109. )
  110. result: ModerationOutputsResult = moderation_factory.moderation_for_outputs(moderation_buffer)
  111. return result
  112. except Exception as e:
  113. logger.error("Moderation Output error: %s", e)
  114. return None