BxDolAiTrigger.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. interface iBxDolAiTrigger
  10. {
  11. public function getType();
  12. /**
  13. * Host entry point (alert, cron, webhook, HTTP).
  14. * @param mixed $mixed host-specific context
  15. */
  16. public function handle($mixed = null);
  17. /**
  18. * Run one agent. Used by handle() and background jobs.
  19. */
  20. public function call($aAgent, $mixedParams = []);
  21. }
  22. class BxDolAiTrigger extends BxDol implements iBxDolAiTrigger
  23. {
  24. protected $_sType = '';
  25. public static function getInstance($sType)
  26. {
  27. if ('chat' === $sType)
  28. $sType = 'manual';
  29. $aMap = [
  30. 'alert' => 'BxDolAiTriggerAlert',
  31. 'message' => 'BxDolAiTriggerMessage',
  32. 'webhook' => 'BxDolAiTriggerWebhook',
  33. 'scheduler' => 'BxDolAiTriggerScheduler',
  34. 'form-input' => 'BxDolAiTriggerFormInput',
  35. 'manual' => 'BxDolAiTriggerChat',
  36. ];
  37. $sClass = $aMap[$sType] ?? 'BxDolAiTrigger';
  38. $sKey = __CLASS__ . '_' . $sType;
  39. if (!isset($GLOBALS['bxDolClasses'][$sKey])) {
  40. $o = new $sClass();
  41. if ('BxDolAiTrigger' === $sClass)
  42. $o->_sType = $sType;
  43. $GLOBALS['bxDolClasses'][$sKey] = $o;
  44. }
  45. return $GLOBALS['bxDolClasses'][$sKey];
  46. }
  47. public function getType()
  48. {
  49. return $this->_sType;
  50. }
  51. public function handle($mixed = null)
  52. {
  53. return false;
  54. }
  55. public function call($aAgent, $mixedParams = [])
  56. {
  57. $oAi = $this->getAi();
  58. if (!$oAi)
  59. return false;
  60. if ($mixedParams)
  61. $sParams = is_string($mixedParams) ? $mixedParams : json_encode($mixedParams);
  62. else
  63. $sParams = 'START';
  64. $sSampleField = $this->getSampleField();
  65. if ($sSampleField && empty($aAgent[$sSampleField])) {
  66. $oDb = new BxDolAiQuery();
  67. $oDb->updateAgentField($aAgent['id'], $sSampleField, $sParams);
  68. }
  69. $aParams = $this->getCallChatHistoryParams($aAgent, $mixedParams);
  70. $sParams = $this->limitCallInput($aAgent, $mixedParams, $sParams);
  71. $oLimits = BxDolAiChatLimits::getInstance();
  72. $oChat = BxDolAiChat::getInstance();
  73. if ($this->appliesChatLimits()) {
  74. if ($oLimits->isChatTurnLimitReached($aAgent, $oLimits->getChatUserTurnCount($aAgent['id'], $aParams))) {
  75. $oChat->emitConversationClosed('limit', '', $aAgent, $aParams);
  76. return $this->getChatLimitReply($aAgent);
  77. }
  78. if ($oLimits->isChatSessionRateLimited($aAgent, $aParams))
  79. throw new Exception($oLimits->getChatSessionRateLimitError());
  80. }
  81. $oChat->setChatContext($aAgent, $aParams);
  82. $mixed = '';
  83. try {
  84. $o = BxDolAi::getAgentInstance($aAgent['id'], $aParams);
  85. if (!$o)
  86. return false;
  87. $oMessage = $o->chat(new NeuronAI\Chat\Messages\UserMessage($sParams))->getMessage();
  88. $mixed = $oMessage->getContent();
  89. } catch (Exception $exception) {
  90. bx_log('sys_agents', "Exception in '{$aAgent['name']}' agent: " . $exception->getMessage() . " INPUT:" . $sParams, BX_LOG_ERR);
  91. $mixed = _t('_sys_agents_exception');
  92. }
  93. return $mixed;
  94. }
  95. protected function getAi()
  96. {
  97. return BxDolAi::getInstance();
  98. }
  99. protected function getSampleField()
  100. {
  101. return '';
  102. }
  103. protected function usesSenderChatHistory()
  104. {
  105. return false;
  106. }
  107. protected function appliesChatLimits()
  108. {
  109. return false;
  110. }
  111. /**
  112. * What call() returns when the thread is at max_turns; null = reply with nothing.
  113. */
  114. protected function getChatLimitReply($aAgent)
  115. {
  116. return BxDolAiChatLimits::getInstance()->getChatLimitMessage($aAgent);
  117. }
  118. protected function getCallChatHistoryParams($aAgent, $mixedParams)
  119. {
  120. if (!$this->usesSenderChatHistory() || !is_array($mixedParams))
  121. return [];
  122. return ['chat_history_subindex' => (int)($mixedParams['sender_profile_id'] ?? 0)];
  123. }
  124. protected function limitCallInput($aAgent, $mixedParams, $sParams)
  125. {
  126. if (!$this->appliesChatLimits())
  127. return $sParams;
  128. $oLimits = BxDolAiChatLimits::getInstance();
  129. if (is_array($mixedParams) && isset($mixedParams['message_text'])) {
  130. $mixedParams['message_text'] = $oLimits->applyChatInputLimit((string)$mixedParams['message_text'], $aAgent);
  131. return json_encode($mixedParams);
  132. }
  133. if (is_string($mixedParams))
  134. return $oLimits->applyChatInputLimit($sParams, $aAgent);
  135. return $sParams;
  136. }
  137. protected function enqueue($aAgent, $mixedParams)
  138. {
  139. BxDolBackgroundJobs::getInstance()->add(bin2hex(random_bytes(16)), [
  140. 'system', 'call_agent',
  141. [$this->getType(), $aAgent, $mixedParams],
  142. 'TemplServices'
  143. ]);
  144. }
  145. protected function runOrEnqueue($aAgent, $mixedParams)
  146. {
  147. if (!empty($aAgent['async'])) {
  148. $this->enqueue($aAgent, $mixedParams);
  149. return null;
  150. }
  151. return $this->call($aAgent, $mixedParams);
  152. }
  153. }
  154. /** @} */